Home > Enterprise >  Get AVAudio Recording URL Before App is Terminated
Get AVAudio Recording URL Before App is Terminated

Time:12-31

I've played with several recording apps and when I swipe to dismiss/terminate while recording, when I come back to the app the audio that was recording prior to the app begin terminated, is available for me to listen to. From my understanding that audio is only available via audioRecorderDidFinishRecording.

In my app I tried to do the same. If a user is recording audio and the app is suddenly terminated (they swipe it away), I stop the recording. But in the delegate audioRecorderDidFinishRecording I can't seem to get the url.

When the app is terminated the docs says we have 5 seconds

Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may terminate the process altogether.

The url usually returns way before 5 seconds but for some reason the recording delegate is never reached. What's the issue? In the example below steps 2 or 5 never get reached.

NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate(notification:)),
                                               name: UIApplication.willTerminateNotification,
                                               object: nil)

@objc func applicationWillTerminate(notification: Notification) {

     if let micRecorder = micRecorder, micRecorder.isRecording {

         micRecorder.stop() // 1. stop recording
     }
}

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {

    // 2. print("if successful the url should be returned")

    if flag {

        let url = recorder.url

        // 3. save url to FileManager then to CoreData

    } else {

        // 4. something went awry
    }
}

func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {

    // 5. print("something went wrong")

    print(error.localizedDescription)
}

CodePudding user response:

When you initialize AVAudioRecorder, you pass it a URL. This URL is where the audio data is recorded. That URL will be the same as the URL that you're attempting to get via the delegate methods.

Instead of trying to retrieve the URL via those delegate methods, you can just store the initial URL that you created or just make sure that you can reliably recreate it.

  • Related