Getting 561015905 while trying to initiate recording when the app is in background

I'm trying to start and stop recording when my app is in background periodically. I implemented it using Timer and DispatchQueue. However whenever I am trying to initiate the recording I get this error. This issue does not exist in foreground.

Here is the current state of my app and configuration.

  1. I have added "Background Modes" capability in the Signing & Capability and I also checked Audio and Self Care. Here is my Info.plist:
<plist version="1.0">
<dict>
	<key>UIBackgroundModes</key>
	<array>
		<string>audio</string>
	</array>
	<key>WKBackgroundModes</key>
	<array>
		<string>self-care</string>
	</array>
</dict>
</plist>

I also used the AVAudioSession with .record category and activated it. Here is the code snippet:

func startPeriodicMonitoring() {
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setCategory(AVAudioSession.Category.record, mode: .default, options: [.mixWithOthers])
            try session.setActive(true, options: [])
            print("Session Activated")
            print(session)
            // Start recording.
            measurementTimer = Timer.scheduledTimer(withTimeInterval: measurementInterval, repeats: true) { _ in
                self.startMonitoring()
                DispatchQueue.main.asyncAfter(deadline: .now() + self.recordingDuration) {
                    self.stopMonitoring()
                }
            }
            measurementTimer?.fire()  // Start immediately
        } catch let error {
            print("Unable to set up the audio session: \(error.localizedDescription)")
        }
    }

Any thoughts on this? I have tried most of the ways but the issue is still there.

Answered by ForumsContributor in
Accepted Answer

Audio recording must begin when the app is in the foreground. The error is telling you that you are trying to start recording when it is not allowed.

Thank you for your reply. At first I started the audio in the foreground and I didn't stop it in the background and it was working. However, due to the high power consumption I decided to change the method to start and stop recording only for some periods. My ultimate goal is to do some analysis on the environment noise and I do not need the microphone to be open at all times. Do you have any suggestion for that?

Getting 561015905 while trying to initiate recording when the app is in background
 
 
Q