簡體   English   中英

如何使用AVAudioPlayer播放“ http:/…/ mp3”

[英]How to play 'http:/… /mp3' with AVAudioPlayer

我無法播放mp3音頻文件。

URL_PATH = @"http://...../.…./A1.mp3";

NSError *錯誤;

player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:URL_PATH] error:&error];
if (error) 
{
    NSLog(@"error:%@",error.localizedDescription);
}

if (player ==nil)
{
    NSLog(@"nil");
}
else 
{
    NSLog(@"playing");
    [player play];
}  

錯誤代碼 :

error:The operation couldn’t be completed. (OSStatus error -43.)
nil

我能怎么做? 請告訴我提示。 謝謝!

您使用了錯誤的播放器來播放從網絡流捕獲的音頻。 請參閱有關AVAudioPlayer Apple文檔:

Apple建議您使用此類播放音頻, 除非您正在播放從網絡流捕獲的音頻或需要非常低的I / O延遲。 有關音頻技術的概述,請參見《多媒體編程指南》中的“音頻和視頻起點”和“使用音頻”。

解決方法使用AVAudioPlayer一種方法是獲取音頻數據並將其放入NSData 然后,您可以通過initWithData:error:初始化AVAudioPlayer 另外,不要將代碼放在主隊列中。 否則,它將阻止您的用戶界面對用戶輸入做出反應。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSURL *mp3URL = [NSURL URLWithString:@"http://zhangmenshiting.baidu.com/data2/music/44799433/4479927746800128.mp3?xcode=dbff90a141d5d136fdc7275fdc3fae126077a44adc974ad8"];
    NSData *data = [NSData dataWithContentsOfURL:mp3URL];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:NULL];
    [self.audioPlayer play];
});

sunkehappy是正確的,AVAudioPlayer並非用於流音頻。 它用於播放音頻文件和已在內存中的數據。 因此,您需要使用數據而不是URL對其進行初始化。

這是蘋果的答案(您可以在這里找到http://developer.apple.com/library/ios/#qa/qa1634/_index.html ):

AVAudioPlayer類不支持基於HTTP URL的流音頻。 與initWithContentsOfURL:一起使用的URL必須是文件URL(file://)。 即一條本地路徑。

如果您尋找音頻流媒體,則可以測試該音頻流媒體

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM