iosswiftavfoundationavaudiorecorder

Sound volume decreasing for no apparent reason


I have an iOS app using SwiftUI. It handles a few sound files and performs some audio recording. This is the function doing the recording work:

func recordAudio(to file: String, for duration: TimeInterval) {
    let audioSession:AVAudioSession = AVAudioSession.sharedInstance()
    
    do {try audioSession.setCategory(.playAndRecord, mode: .default)
        try audioSession.setActive(true)
        
        let audioFilename = getDocumentsDirectory().appendingPathComponent(file+".m4a"),
            audioURL = URL(fileURLWithPath: audioFilename),
            settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 2,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
                ]

        audioRecorder = try AVAudioRecorder(url: audioURL, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record(forDuration: TimeInterval(2.0))
    } catch let error as NSError {
        print("Failed -- Recording !!! -> \(error)")
    }
}

At this point, it basically works, but there is a strange behaviour that I neither understand nor like.

Here is the problem:

When I start the app and play a sound file, the volume is right for my taste. Then without ever adjusting the volume I perform some recording (using the function above). Finally after the recording is done, I go back to the file I played just before and play it again; the volume has mysteriously gone down, without me knowing why.

Is there something in my function that could explain that? Or some other cause that someone could think of?

If I restart the app, the volume automatically goes back to normal. For information, I am using iOS 14.4.2 and Xcode 12.4.


Solution

  • The audio session will be a decreased volume during playback after recording in .playAndRecord mode. After recording, explicitly set to something like .playback to get the volume you're expecting.