iOS AVAudioPlayer没有播放

时间:2012-08-25 21:30:47

标签: ios avfoundation avaudioplayer

此代码:

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

什么都不玩!

出了什么问题?

1 个答案:

答案 0 :(得分: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 */
        }
    }
}