1

This is the code I have right now for pausing a recording when a user receives a phone call and resuming it after they hang up.

- (void)handleAudioSessionInterruption:(NSNotification *)notification
{
  NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];

  switch (interruptionType.unsignedIntegerValue) {
    case AVAudioSessionInterruptionTypeBegan:{
      _currentAudioSessionMode = EXAVAudioSessionModeInactive;
      if (_audioRecorder.recording) {
        [_audioRecorder pause];
        [self demoteAudioSessionIfPossible];
      }
    } break;
    case AVAudioSessionInterruptionTypeEnded:{
      _currentAudioSessionMode = EXAVAudioSessionModeActive;
      if (_audioRecorder && !_audioRecorder.recording) {
        if (_allowsAudioRecording) {
          [self promoteAudioSessionIfNecessary];
          _audioRecorderShouldBeginRecording = true;
          [_audioRecorder record];
        }
      _audioRecorderShouldBeginRecording = false;
      }
    } break;
    default:
      break;
  }

What I would like to achieve is to keep recording, but capture pure silence while a user is on a phone call. This is how it works on Android and we care about the correct duration of the recording. Any idea how to do it?

1 Answers1

0
#import <AVFoundation/AVFoundation.h>

Set up the audio session to use the AVAudioSessionCategoryPlayAndRecord category and activate it:

  AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

[audioSession setActive:YES error:nil];

Set up the audio recorder using the AVAudioRecorder class, specifying the URL where the audio file will be saved and the audio settings for the recording:

NSURL *url = [NSURL fileURLWithPath:@"/path/to/audio/file.m4a"];
NSDictionary *settings = @{
    AVFormatIDKey: @(kAudioFormatMPEG4AAC),
    AVSampleRateKey: @44100.0f,
    AVNumberOfChannelsKey: @1,
};
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:nil];

Start the recording by calling the record method on the audio recorder:

[recorder record];

To stop the recording, call the stop method on the audio recorder:

[recorder stop];

To record silence while the user is on a phone call, you can use the audioRecorderDidFinishRecording:successfully: delegate method to detect when the recording has stopped due to the phone call and start a new recording.

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    // Check if the recording was stopped due to a phone call
    if (!flag) {
        // Start a new recording
        [recorder record];
    }
}
Zagham Arshad
  • 111
  • 1
  • 7