Search code examples
iosaudiorecordplayback

iOS How to play alert sound in speaker when recording


I want to manually trigger to play some alert sound during recording audio, and I want the alert sound be recorded. So I want the alert play loudly in speaker instead of Receiver during recording audio.

I use AVAudioRecorder to record audio and use AVAudioPlayer to play the alert sound. Code for recorder

AVAudioSession *session = [AVAudioSession sharedInstance];

NSError *sessionError;
[session setCategory:AVAudioSessionCategoryRecord error:&sessionError];

if(session == nil)
    NSLog(@"Error creating session: %@", [sessionError description]);
else
    [session setActive:YES error:nil];
recorder = [[AVAudioRecorder alloc] initWithURL:_recordedFile settings:recordSettings error:nil];
[recorder prepareToRecord];
[recorder record];

Code for player

    AVAudioSession *session = [AVAudioSession sharedInstance];
// session.outputDataSources
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];

// use the louder speaker
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
                         sizeof (audioRouteOverride),&audioRouteOverride);

if(session == nil)
    NSLog(@"Error creating session: %@", [sessionError description]);
else
    [session setActive:YES error:nil];

NSError *error;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.filePath error:&error];
player.delegate =self;
player.volume = 1.0;
player.numberOfLoops = 0;
self.timeDuration = player.duration;

If I stop the recording, and manually trigger the play alert, it plays in speaker. But during recording, when I manually trigger the play alert, nothing happens. Is there anything wrong here? Or Is it possible to play sound in speaker when recording?


Solution

  • Just change category as below thats all

    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];