iOS AVAudioPlayer没有播放

Has*_*mad 1 avfoundation avaudioplayer ios

这段代码:

NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"snd" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:urlPath];

NSError *err;

AVAudioPlayer* audioPlayerMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];

[audioPlayerMusic play];
Run Code Online (Sandbox Code Playgroud)

工作得很好.

这一个:

NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"snd" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:urlPath];

AVPlayer* audioPlayerMusic = [AVPlayer playerWithURL:url];

[audioPlayerMusic play];
Run Code Online (Sandbox Code Playgroud)

什么都不玩!

出了什么问题?

小智 8

播放/流式传输远程文件时,AVPlayer尚未准备好播放它 - 您必须等待它缓冲足够的数据才能开始付费,而使用AVAudioPlayer则不需要这样做.因此,要么使用AVAudioPlayer,要么让AVPlayer在准备开始播放时使用键值观察来通知您的类:

[player addObserver:self forKeyPath:@"status" options:0 context:NULL];
Run Code Online (Sandbox Code Playgroud)

在你的班级(self指上一行中的实例):

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        if (player.status == AVPlayerStatusReadyToPlay) {
            [player play];
        } else if (player.status == AVPlayerStatusFailed) {
            /* An error was encountered */
        }
    }
}
Run Code Online (Sandbox Code Playgroud)