1

这段代码:

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

工作得很好。

虽然这个:

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

AVPlayer* audioPlayerMusic = [AVPlayer playerWithURL:url];

[audioPlayerMusic play];

什么都不玩!

怎么了?

4

1 回答 1

8

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

[player addObserver:self forKeyPath:@"status" options:0 context:NULL];

在你的类中(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 */
        }
    }
}
于 2012-08-25T21:51:05.467 回答