简体   繁体   中英

How to play 'http:/… /mp3' with AVAudioPlayer

I can't play mp3 audio file.

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

NSError *error;

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 code :

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

How can I do? Please tell me hint. pre-Thanks!

You are using the wrong player to play audio captured from a network stream. See Apple's documentation on AVAudioPlayer :

Apple recommends that you use this class for audio playback unless you are playing audio captured from a network stream or require very low I/O latency. For an overview of audio technologies, see Audio & Video Starting Point and “Using Audio” in Multimedia Programming Guide.

One work around way to use AVAudioPlayer is to fetch the audio's data and put it in a NSData . Then you can init your AVAudioPlayer by initWithData:error: . Also, don't put the code in your main queue. Else it will block your user interface from reacting to user's input.

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 is right, AVAudioPlayer isn't meant for streaming audio. It is meant for playing audio files and for data that is already in memory. That's why you need to init it with the data and not with the URL.

Here's the apple answer (which you can find here http://developer.apple.com/library/ios/#qa/qa1634/_index.html ):

The AVAudioPlayer class does not provide support for streaming audio based on HTTP URL's. The URL used with initWithContentsOfURL: must be a File URL (file://). That is, a local path.

If you look for an audio streamer, you can test that audio streamer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM