Iulian Onofrei Iulian Onofrei - 4 months ago 31
Objective-C Question

AVAudioPlayer initialization with web URL crashes

I have a sound file on a server and I try to play it on device.

Using this code:

NSURL audioURL = [NSURL URLWithString:@"http://..."];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error]


crashes with the error:


Description of exception being thrown: '-[NSTaggedPointerString getCharacters:range:]: Range {0, 12} out of bounds; string length 5


The url has the length
73
.

Firstly, why is it crashing instead of populating my
error
object?

If I use this code:

NSURL audioURL = [NSURL URLWithString:@"http://..."];
NSData *audioData = [NSData dataWithContentsOfURL:audioURL];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:audioData error:&error]


it works.

Looking at the name of the methods, it looks like they do the same thing, so why isn't the first method working?
Reading the
AVAudioPlayer
init methods' documentation reveals nothing related to this problem.

Answer

Are you streaming your audio file? AVAudioPlayer cannot stream from URL. You can use it with files stored on device. If you want to stream your file from URL you need to use AVPlayer The following code:

AVPlayerItem *item = [AVPlayerItem playerItemWithURL: audioURL];
AVPlayer *myAVPlayer = [AVPlayer playerWithPlayerItem: item];

EDIT

When you are going to use your AVAudioPlayer with URL you need to present your URL like this:

NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@"myMusic" ofType:@"mp3"];
NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];

Taken from here

Hope it will help

Comments