2010-09-03 47 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 
相關問題