I am trying to record and play audio simultaneously using the playAndRecord AvAudioSessionCategory. I have found other stack overflow posts about this but they have either been outdated or don't work for the code I have written. When I just use the playback category I am able to successfully play back audio. When I set it to playAndRecord audio no longer plays. The program runs but I am met with this error during runtime:
Output will be downmixed to mono: Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"
This is the code for playing the audio. It is in viewDidLoad and runs automatically when the app is opened.
recordingSession = AVAudioSession.sharedInstance()
        do {
            guard let url = Bundle.main.url(forResource: "7s_sinesweeps", withExtension: "wav") else {return}
            print( "I am going to play audio")
            try recordingSession.setCategory(AVAudioSession.Category.playAndRecord
                , mode: AVAudioSession.Mode.default)
            try recordingSession.setActive(true)
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.play()
        }
        catch {
            print("error in player")
        }
I am also having issues with recording the audio, even when I just have the AVAudioSessionCategory set to record. Here is the code for recording the audio:
        do {
recordingSession.setCategory(AVAudioSession.Category.record
                , mode: AVAudioSession.Mode.default)
            try recordingSession.setActive(true)
            recordingSession.requestRecordPermission() { [unowned self] allowed in
                DispatchQueue.main.async {
                    if allowed {
                       self.beginRecording()
                    } else {
                        // failed to record!
                    }
                }
                print("I am going to record")
            }
        } catch {
            // failed to record!
        }
The method it calls is beginRecording which is included below:
func beginRecording() {
    let fileMgr = FileManager.default
    let dirPaths = fileMgr.urls(for: .documentDirectory,
                                in: .userDomainMask)
    let url = dirPaths[0].appendingPathComponent("sound.wav")
    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]
    do {
        audioRecorder = try AVAudioRecorder(url: url, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.prepareToRecord()
        audioRecorder.record(forDuration: 1.0)
    } catch {
        return
    }
}
 
Comments
Post a Comment