views:

34

answers:

2
NSError *err;

// Initialize audio player
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];

audioPlayer.delegate = self;
[audioPlayer play];

With the code above, I'm trying to initialize playback of a .mp3 file, however the playback does not start at all. There is no sound. What am I doing wrong? I have inspected 'err' and there is nothing there.

Edit: After adding AVAudioSession, I'm getting the following error from AVAudioPlayer

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

Did you initialize a AVAudioSession?

The following works fine for me. Might give you a hint of whats not working for you.

Initializing:

AVAudioSession* session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryAmbient error:nil];
[session setActive:TRUE error:nil]; 

Loading:

AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
audioPlayer.numberOfLoops = 0;
[audioPlayer prepareToPlay];
audioPlayer.volume = 1.0;

Playing:

[audioPlayer play];

Update

To find the right NSRUL for fileUrl, I used this code:

NSURL* fileUrl = [NSURL fileURLWithPath:
     [[NSBundle mainBundle] pathForResource:@"MySound" ofType:@"wav"] isDirectory:NO];

And then I added MySound.wav to the project (bundle).

Martin Ingvar Kofoed Jensen
I tried using AVAudioSession as well, but now I'm only getting this error;The operation couldn’t be completed. (OSStatus error -43.)
eriktm
I have the above code working with both mp3's and waves. Try another file, a .wav file.
Martin Ingvar Kofoed Jensen
+1  A: 

Apparently AVAudioPlayer does not support streaming via. HTTP as I was trying to do, so by using AVPlayer instead, I got it working.

eriktm