如何在iPhone应用程序中播放循环声音

Playing Sound

Here is a very useful code snippet for playing your own sound file continuously in your iPhone application. The example uses a .caf file and is based on the AVAudioPlayer Class. You can find the class reference of Apple here: http://developer.apple.com/iPhone/library/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html

这是一个非常有用的代码片段,可用于在iPhone应用程序中连续播放自己的声音文件。 该示例使用.caf文件,并且基于AVAudioPlayer类。 您可以在这里找到Apple的类参考: http : //developer.apple.com/iPhone/library/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html

Let’s assume that you have a view controller where you want to play some sound. I will first start by the header file of your view controller and then move on to the methods in your class MyViewController.m.

假设您有一个要在其中播放声音的视图控制器。 我将首先从视图控制器的头文件开始,然后再转到类MyViewController.m中的方法。

In the header file MyViewController.h we will define the audio player first:

在头文件MyViewController.h中,我们将首先定义音频播放器:

#import <UIKit/UIKit.h>

@interface MyViewController : UIViewController {
    AVAudioPlayer *player;
}

@property (nonatomic, retain) AVAudioPlayer *player;

@end

In MyViewController.m we want to load the sound file from our project and allocate the AVAudioPlayer. Further, we will want to define the looping behavior and the volume. This is how we integrate all that in MyViewController.m:

在MyViewController.m中,我们要从项目中加载声音文件并分配AVAudioPlayer。 此外,我们将要定义循环行为和音量。 这就是我们将所有内容集成到MyViewController.m中的方式

#import "MyViewController.h"

@interface MyViewController()
    -(void)playSound;
@end

@implementation MyViewController

@synthesize player;

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *soundFilePath = 
      [[NSBundle mainBundle] pathForResource: @"mySound" ofType: @"caf"];
    NSURL *fileURL = 
      [[NSURL alloc] initFileURLWithPath: soundFilePath];
    AVAudioPlayer *newPlayer = 
      [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
    [fileURL release];
    self.player = newPlayer;
    [newPlayer release];
}	

- (void)viewWillAppear:(BOOL)animated{
    player.numberOfLoops = -1;
    player.currentTime = 0;
    player.volume = 1.0;
    [self playSound];
}

- (void)viewWillDisappear:(BOOL)animated{
    if (self.player.playing) {
        [self.player stop];
    }
}

- (void) playSound{
    [self.player play];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (void)dealloc {
    [super dealloc];
    [player release];
}

@end

Setting numberOfLoops to a negative integer will make your sound loop until you call stop to terminate the playing of the sound. The currentTime is the moment from when you want to play the sound in seconds. So zero means that you want to start from the beginning. The method playSound will call play to actually play the sound.

numberOfLoops设置为负整数将使您的声音循环,直到您调用stop终止声音播放为止。 currentTime是从几秒钟开始播放声音的时刻。 因此,零表示您要从头开始。 playSound方法将调用play来实际播放声音。

Check out the class reference for more options, like pausing your sound or playing more sounds simultaneously. I hope it helped! Enjoy!

请查阅课程参考,以了解更多选项,例如暂停声音或同时播放更多声音。 希望对您有所帮助! 请享用!

翻译自: https://tympanus.net/codrops/2009/09/15/how-to-play-sound-in-your-iphone-app/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一个简单的录音和播放程序。请按照以下步骤操作: 1. 创建一个新的 Xcode 项目,选择 Single View App 模板,语言选择 Swift。 2. 在 Main.storyboard 添加两个按钮(录音和播放)和一个标签,用于显示录音和播放状态。 3. 在 ViewController.swift 文件添加以下代码: ```swift import UIKit import AVFoundation class ViewController: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate { @IBOutlet weak var statusLabel: UILabel! var audioRecorder: AVAudioRecorder? var audioPlayer: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() setupRecorder() } func setupRecorder() { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSession.Category.playAndRecord) try audioRecorder = AVAudioRecorder(url: getFileURL(), settings: getAudioSettings()) audioRecorder?.delegate = self audioRecorder?.prepareToRecord() } catch { print("Error setting up audio recorder: \(error.localizedDescription)") } } func getFileURL() -> URL { let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let audioURL = documentsDirectory.appendingPathComponent("recording.caf") return audioURL } func getAudioSettings() -> [String: Any] { let settings = [ AVFormatIDKey: NSNumber(value: kAudioFormatAppleLossless), AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue, AVEncoderBitRateKey: 320000, AVNumberOfChannelsKey: 2, AVSampleRateKey: 44100.0 ] return settings } @IBAction func startRecording(_ sender: UIButton) { if audioRecorder?.isRecording == false { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setActive(true) audioRecorder?.record() statusLabel.text = "Recording..." } catch { print("Error starting recording: \(error.localizedDescription)") } } } @IBAction func stopRecording(_ sender: UIButton) { if audioRecorder?.isRecording == true { audioRecorder?.stop() let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setActive(false) statusLabel.text = "Recording stopped" } catch { print("Error stopping recording: \(error.localizedDescription)") } } } @IBAction func playRecording(_ sender: UIButton) { if audioPlayer?.isPlaying == false { do { try audioPlayer = AVAudioPlayer(contentsOf: getFileURL()) audioPlayer?.delegate = self audioPlayer?.play() statusLabel.text = "Playing..." } catch { print("Error playing audio: \(error.localizedDescription)") } } } func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if flag { statusLabel.text = "Recording saved" } else { statusLabel.text = "Recording failed" } } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { if flag { statusLabel.text = "Playback finished" } else { statusLabel.text = "Playback failed" } } } ``` 这段代码包括了以下内容: - 创建 AVAudioRecorder 和 AVAudioPlayer 实例来处理录音和播放 - 设置录音的 URL 和参数 - 设置录音和播放的按钮动作 - 显示录音和播放状态的标签 - 实现 AVAudioRecorderDelegate 和 AVAudioPlayerDelegate 来处理录音和播放完成后的事件 4. 运行应用程序并在iPhone测试录音和播放功能。 请注意,这只是一个简单的示例,您可以根据您的需求进行修改和扩展。同时,您需要确保在应用程序的 Info.plist 文件添加了麦克风和音频播放权限,否则应用程序将无法访问麦克风或播放音频文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值