0

我需要在打开视图后自动播放音频并有一个按钮来控制播放/暂停事件。我听说它有一个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;


}
}

是否可以使用按钮自动播放音频和播放/暂停?如何?

4

1 回答 1

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 文档

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

准备播放 >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.

希望这可以帮助

于 2013-06-13T11:32:32.150 回答