使用AVAudioPlayer播放来自互联网的audio

我正在实现AVAudioPlayer播放audio,并且在播放本地存储在PC中的文件时效果非常好。

但是,当我通过互联网给一些audio文件的url,它伤心地失败。 这是代码的样子:

NSString *url = [[NSString alloc] init]; url = @"http://files.website.net/audio/files/audioFile.mp3"; NSURL *fileURL = [[NSURL alloc] initWithString: url]; AVAudioPlayer *newPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil]; 

有谁能指出这个问题,可以做些什么?
谢谢!

我在AVAudioPlayer而不是initWithContentsOfURL尝试其他方法initWithData。 首先尝试将MP3文件转换为NSData,然后播放此数据。

看看我的代码在这里 。

使用AVPlayer基于http url的stream式传输audio/video。 它会正常工作。 AVAudioPlayer用于本地文件。 这是代码

 NSURL *url = [NSURL URLWithString:url]; self.avAsset = [AVURLAsset URLAssetWithURL:url options:nil]; self.playerItem = [AVPlayerItem playerItemWithAsset:avAsset]; self.audioPlayer = [AVPlayer playerWithPlayerItem:playerItem]; [self.audioPlayer play]; 

这就是苹果公司的文档所说的:

AVAudioPlayer类不支持基于HTTP URL的audiostream。 用于initWithContentsOfURL:的URL必须是文件URL( file:// )。 那就是一个本地path。

使用AVPlayer并监视其状态以开始播放。

这是一个可行的例子,希望这会有所帮助。

 @implementation AudioStream - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { if (context == PlayerStatusContext) { AVPlayer *thePlayer = (AVPlayer *)object; switch ([thePlayer status]) { case AVPlayerStatusReadyToPlay: NSLog(@"player status ready to play"); [thePlayer play]; break; case AVPlayerStatusFailed: NSLog(@"player status failed"); break; default: break; } return; } else if (context == ItemStatusContext) { AVPlayerItem *thePlayerItem = (AVPlayerItem *)object; switch ([thePlayerItem status]) { case AVPlayerItemStatusReadyToPlay: NSLog(@"player item ready to play"); break; case AVPlayerItemStatusFailed: NSLog(@"player item failed"); break; default: break; } return; } [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } - (void)playAudioStream { NSURL *audioUrl = [NSURL URLWithString:@"your_stream_url"]; AVURLAsset *audioAsset = [AVURLAsset assetWithURL:audioUrl]; AVPlayerItem *audioPlayerItem = [AVPlayerItem playerItemWithAsset:audioAsset]; [audioPlayerItem addObserver:self forKeyPath:@"status" options:0 context:ItemStatusContext]; self.player = [AVPlayer playerWithPlayerItem:audioPlayerItem]; [self.player addObserver:self forKeyPath:@"status" options:0 context:PlayerStatusContext]; } @end