循环.wav文件

时间:2015-03-31 19:54:58

标签: ios audio wav

我正在为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.
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用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];