AVAudioPlayer hiccups the app sometimes

2019-09-16 06:27发布

问题:

I am working on a simple game and after every screen touch, an animation is happening on a small UIImageView and this happen very well and the app is running smoothly with CADisplayLink as the timer.

I added an mp3 file to play after every touch with 1 second lengh as AVAudioPlayer imagine a sound like : Bip

So the first time that I touch the screen first hiccup happens an the app freeze for less than a second that I can say it is ok coz it's the first time that the sound allocate memory.

The problem happens later when u touch the screen again if I touch it earlier than 3 seconds, the app doesn't hiccups but if I wait 4 seconds and more, the app starts to hiccup after every touch.

Every time if I touch again and again earlier than 3 seconds between touches, the app doesn't hiccups, but after 4 seconds between touches, the app hiccups.

Any idea to solve hiccups?

This is some code if needed

@property (nonatomic, strong) AVAudioPlayer *mySound;

- (void)viewDidLoad {

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"bip" ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];

self.mySound = newPlayer;

[mySound prepareToPlay];
[mySound setDelegate:self];
}

and after touch happens

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];
if (location.x < viewWidth/2) {
   [mySound play];
} else {
   [mySound play];
}
}

回答1:

Make a very short silent sound. Use your timer to play that (with another sound player) every second or so. — You see what the idea is here; we are try to keep the media server alive so that it is ready to go when we want our sound effect. Since you say there's no problem before 3 seconds, that makes me think that after 3 seconds the media server has gone back to sleep. Our goal is to keep "tickling" it so that can't happen.

In general, however, my impression is that AVAudioPlayer is not intended for this sort of thing. You should probably be using AVAudioEngine, which can be kept running and made to play sounds without latency.