How to start audio recording when app running on background?

I am working on audio recording. when application running on foreground i have to start audio recording and going to background at that time audio recording working fine.

But my question is that how to start audio recording when i am already in background, My audio recording function fired like this:

I have a Bluetooth LE device with buttons and an iOS app. Those two are paired (Bluetooth LE device and the iPhone which runs the iOS app) and the iOS app is listening for events on the Bluetooth LE device, events like a hit of a button.

Now, when the user hits a button on the Bluetooth LE device, the iOS app captures the event and I am able to run code even if the app is in background, but I am not able to start a voice recording.

I have already enable Background Modes:

Here is my Code for Audio Recording:

func startRecording() {
        
        DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime.now(), qos: .background) {
            let audioFilename = self.getDocumentsDirectory().appendingPathComponent("recording.m4a")
            print("record Audio \(audioFilename)")
            let settings = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 12000,
                AVNumberOfChannelsKey: 1,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]

            do {
                self.audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
                self.audioRecorder.delegate = self
                self.audioRecorder.record()
            } catch {
                self.finishRecording(success: false)
            }
        }
    }

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
  }

I can't find proper solution to do that thing, Please suggest me proper way to do that, Thanks in Advance.

I also have the same problem... Did you solve this?

Hi ,

I'm facing same issue in my SwiftUI project ,

below is my code

func startRecording(isEmergency:Bool = false) {

    guard !(self.audioRecorder?.isRecording ?? false) else { return }
    
    self.audioFileName = isEmergency ? "emergencyRecording" : "recording"
    self.recordeAudioURL = nil
    
    AVAudioSession.sharedInstance().requestRecordPermission { flag in
         
        guard flag else { return }
        var audioFileURL:URL?
        var settings: [String: Any] = [:]
        do {
            
            // Enable background audio
            try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetoothA2DP, .allowBluetooth, .allowBluetoothA2DP, .allowAirPlay, .mixWithOthers])
            try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)

            if self.audioFormate == .m4a {
                audioFileURL = self.getDirectory()?.appendingPathComponent(self.audioFileNameWithExtention)
                settings = [
                    AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                    AVSampleRateKey: 44100,
                    AVNumberOfChannelsKey: 2,
                    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
                ]
            } else if self.audioFormate == .mp3 {
                audioFileURL = self.getDirectory()?.appendingPathComponent(self.audioFileNameWithExtention)
                settings = [
                    AVFormatIDKey: kAudioFormatLinearPCM,
                    AVSampleRateKey: 44100,
                    AVNumberOfChannelsKey: 2,
                    AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue
                ]
            }
            
            guard let audioURL = audioFileURL  else { return }
            
            self.audioRecorder = try AVAudioRecorder(url: audioURL, settings: settings)
            self.audioRecorder?.delegate = self
            
            self.audioRecorder?.prepareToRecord()
            self.audioRecorder?.record()
            
            self.isAudioRecording = true
            self.recordeAudioURL = audioFileURL
            
            //MARK: Start background task
            self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
                       
            self.checkAudioIsRecording()
            
            AppDelegate.shared?.sendLocalNotification(title: "YODDA",
                                       message: "Recording Started...",
                                       identifier: "AudioRecording")
            
        } catch {
            self.recordeAudioURL = nil
            self.stopRecording()
            print("Error starting recording: \(error.localizedDescription)")
        }
        
    }
    
}
How to start audio recording when app running on background?
 
 
Q