2010-09-03 48 views
6

我正在实现AVAudioPlayer播放音频,并且在播放本地存储在PC中的文件时,它工作得非常好。使用AVAudioPlayer播放来自互联网的音频

但是,当我通过互联网给一些音频文件的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]; 

有谁请指出问题所在,什么可以做?
谢谢!

+0

您是否试图提供错误对象以查看它是否包含错误描述? – Toastor 2010-09-03 12:47:26

+0

不,但应用程序不会崩溃...只是视图出现,没有任何反应。 – Bangdel 2010-09-03 13:12:18

回答

2

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

看看我的代码here

17

这就是苹果的文档说:

AVAudioPlayer类不提供基于HTTP URL的音频流的支持。与initWithContentsOfURL:一起使用的URL必须是文件URL(file://)。那就是一个本地路径。

27

使用AVPlayer基于http url的流式传输音频/视频。它会正常工作。 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]; 
0

使用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 
相关问题