这段代码:
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];
什么都不玩!
怎么了
最佳答案
在播放/流式传输远程文件时,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 */
}
}
}
关于ios - iOS AVAudioPlayer无法播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12125808/