Search code examples
iosobjective-caudioavplayer

Play 2 audios at same time objective-c


I have a AVPlayer running with a livestream form a camera and I want to play another audio(camera snapshot audio effect), when the user touch a button to take a snapshot

So I added this code

- (void)screenFlash {
NSString *soundFilePath = [NSString stringWithFormat:@"%@/Snapshoot.m4a",[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = 1;

[player play];

UIView *flash = [[UIView alloc] initWithFrame:self.view.frame];
flash.backgroundColor = UIColor.whiteColor;
flash.alpha=1;

[self.view addSubview:flash];

[UIView animateWithDuration:0.3 animations:^{
    flash.alpha=0;
} completion:^(BOOL finished) {
    [flash removeFromSuperview];
}];
}

If I put a breakpoint just before the [player play], the audio sounds perfectly but if I disable the breakpoint the audio doesn't reproduce.

Someone knows why? Can I play two audios (camera audio & the snapshot effect) at same time?


Solution

  • You could use something like this for playing camera snapshot audio effect. Works perfect for me.

     #import <AudioToolbox/AudioToolbox.h>
     ......................................
     AudioServicesPlaySystemSound(1108);