Strange behavior with AVAudioPlayer on iPhone

I am trying to play audio using AVAudioPlayer. Should be simple, but I am seeing some odd results.

the code:

NSString *path = [[NSBundle mainBundle] pathForResource:@"pop" ofType:@"wav"];
NSURL *url = [NSURL fileURLWithPath:path];
AVAudioPlayer *sound = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[sound play];
[sound release];

      

I can see that no sound is playing during normal use of the app.

It only reproduces if I step through the code using the debugger, it doesn't reproduce when I do the other way ...

I am not creating any new threads or launches in my application, so this should all be done on the main thread, at least [NSThread isMainThread]

returns true.

Anyone have any ideas as to what is going on here?

0


a source to share


2 answers


The AVAudioPlayer method play

is asynchronous, so you start playing the sound and then immediately release it! This is why it works when you go through it in the debugger - you give it time to play before you kill it. What you want to do is implement the AVAudioPlayerDelegate method - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

and free the audio player there after the audio has been played.



+4


a source


papajohn is right, you should do it like this

You have an audio player level variable like

AVAudioPlayer *classLevelPlayer;

      

synthesize this object. and when calling the player method



-(void)playTheSong{

if(classLevelPlayer!=nil){
[classLevelPlayer stop];
[self setClassLevelPlayer:nil];
}

NSString *path = [[NSBundle mainBundle] pathForResource:@"pop" ofType:@"wav"];
NSURL *url = [NSURL fileURLWithPath:path];

AVAudioPlayer *sound = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

if(sound){
[self setClassLevelPlayer:sound];
[classLevelPlayer play];
}
[sound release];
}

      

and in

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
 [self setClassLevelPlayer:nil];
}

      

Hope it helps.

0


a source







All Articles