ios - iOS AVAudioPlayer无法播放

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

什么都不玩!

怎么了

最佳答案

在播放/流式传输远程文件时,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/

相关文章:

iphone - iOS:在后台同时运行应用程序音频和电话音乐音频

ios - 为什么 beginUpdates 不调整 UITableView 中单元格的大小?

ios - AVMutableComposition - 连接的视频 Assets 在第一个 Assets 后停止

ios - 使用 Swift 进行视频缓冲输出

ios - 在 iOS 上没有任何延迟地一个接一个地播放声音

ios - 如何从 ViewDidLoad 中的警报 View 获取文本字段值? iOS 5 代码

ios - 使用 AVPlayer 从互联网流式传输视频时,用户界面卡住

swift - 使用 AVMutableComposition 和 AVAssetExportSession 创建的 MP4 视频在 Quicktime 中工作,但在所有其他视频工具中显示损坏

ios - AVAudioSession 重新激活问题

swift - 声音导致游戏在 swift sprite 套件游戏中滞后?