是否可以通过按钮自动播放音频和播放/暂停?

时间:2013-06-13 11:23:59

标签: iphone objective-c uibutton avaudioplayer

打开视图后我需要自动播放音频,并有一个按钮来控制播放/暂停事件。我听说它有一个prepareToPlay按钮来控制音频但它不能自动播放音频。 这是我的代码:

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                     pathForResource:@"track8"
                                     ofType:@"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

[audioPlayer prepareToPlay];

并按下按钮:

-(IBAction)playPauseButtonPress:(id)sender{

if (self.isPlaying) {

    [self.audioPlayer pause];

    self.isPlaying = NO;

}else {
    [self.audioPlayer play];

    self.isPlaying = YES;


}
}

是否可以使用按钮自动播放音频和播放/暂停?怎么样?

1 个答案:

答案 0 :(得分:0)

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                 pathForResource:@"track8"
                                 ofType:@"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

[audioPlayer prepareToPlay];

方法play可用于播放。您只需添加以下行:

[audioPlayer play];

请查看AVAudioPlayer documentation

播放> Calling this method implicitly calls the prepareToPlay method if the audio player is not already prepared to play.

prepareToPlay> Calling this method preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the play method and the start of sound output.Calling the stop method, or allowing a sound to finish playing, undoes this setup.

如果您使用play代替prepareToPlay,则无法暂停音频。

希望这有帮助

相关问题