Iulian Onofrei Iulian Onofrei - 1 year ago 136
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

Firstly, why is it crashing instead of populating my

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
init methods' documentation reveals nothing related to this problem.

Answer Source

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];


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download