循环 .wav 文件

Looping .wav file

我正在为 iPhone 制作一个闹钟应用程序,并且想要连续循环播放音频直到再次按下按钮。到目前为止,它所做的只是在按下时播放一次音频。这是代码:

-(IBAction)PlayAudioButton:(id)sender {

AudioServicesPlaySystemSound(PlaySoundID);

}

- (void)viewDidLoad {

NSURL *SoundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"wav"]];

AudioServicesCreateSystemSoundID((__bridge CFURLRef)SoundURL, &PlaySoundID);

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

有什么建议吗?

使用AVAudioPlayer播放声音。您必须将 AVFoundation.framework 添加到您的项目才能使其生效。首先声明一个 AVAudioPlayer 对象。它必须声明为具有 strong 属性的 属性,例如

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

或作为具有 __strong 属性的实例变量

@interface Class : SuperClass //or @implementation Class
{
    AVAudioPlayer __strong *audioPlayer;
}

然后,加载并播放文件,

- (void)viewDidLoad
{
    NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"wav"];
    NSURL *audioFileURL = [NSURL fileURLWithString:audioFilePath];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil];
    audioPlayer.numberOfLoops = -1; //plays indefinitely
    [audioPlayer prepareToPlay];
}


- (IBAction)PlayAudioButton:(id)sender
{
    if ([audioPlayer isPlaying])
        [audioPlayer pause]; //or "[audioPlayer stop];", depending on what you want
    else
        [audioPlayer play];
}

并且,当您想停止播放声音时,调用

[audioPlayer stop];