AVAudioPlayer will not play repeatedly

I have a relatively simple application that plays sound using AVAudioPlayer , for example:

 NSURL *file3 = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/ball_bounce.aiff", [[NSBundle mainBundle] resourcePath]]]; player3 = [[AVAudioPlayer alloc] initWithContentsOfURL:file3 error:nil]; [player3 prepareToPlay]; 

to be called later for playback, for example:

 [player3 play]; 

But this sound is called in several places (collisions with a bouncing ball), many times. Sometimes the ball hits two things in a fairly fast sequence when the sound from the first bounce is still playing, when the ball collides for the second time. This second rebound then does not produce sound. How can I make it play a sound every time it collides, even if it involves paying for a sound that overlaps an already playing sound?

Any help is greatly appreciated.

+6
source share
2 answers

One way to solve this problem is to create a new instance of AVAudioPlayer if the previous one is already playing:

 if([player3 isPlaying]) { AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[player3 url]]; [newPlayer setDelegate:self]; [newPlayer play]; } 

Then in the delegate method audioPlayerDidFinishPlaying:successfully: you must send the player a -release message:

 - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { if(player != player3) { [player release]; } } 

This is as it should be, since you need a new source buffer for each sound playing simultaneously .:(

+3
source

This is an old thread, but maybe someone can take advantage of this answer. Creating AVAudioPlayer can repeatedly be a burden on an application and can create delays. In this case, you can use SystemSound.

 NSString *pathToMySound = [[NSBundle mainBundle] pathForResource:@"yourMusic" ofType:@"mp3"]; SystemSoundID soundID; AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath: pathToMySound]), &soundID); AudioServicesPlaySystemSound(soundID); 

At the bottom of this solution, you cannot adjust the volume.

0
source

Source: https://habr.com/ru/post/890828/


All Articles