Post

Replies

Boosts

Views

Activity

Reply to How to start audio recording when app running on background?
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)") } } }
May ’24