在应用程序终止之前获取 AVAudio 录音 URL

Get AVAudio Recording URL Before App is Terminated

我玩过几个录音应用程序,当我在录音时滑动到 dismiss/terminate 时,当我回到应用程序时,应用程序开始终止之前正在录制的音频可供我使用听。据我了解,音频只能通过 audioRecorderDidFinishRecording.

获得

在我的应用程序中,我尝试做同样的事情。如果用户正在录制音频并且应用程序突然终止(他们将其滑开),我将停止录制。但是在委托中 audioRecorderDidFinishRecording 我似乎无法获得 url.

当应用程序终止时,docs 表示我们有 5 秒

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.

url 通常在 5 秒之前 returns 方式,但由于某种原因从未达到记录代表。有什么问题?在下面的示例中,永远不会达到步骤 2 或 5。

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)
}

当你初始化 AVAudioRecorder 时,你传递给它一个 URL。这个 URL 是记录音频数据的地方。 URL 将与您尝试通过委托方法获得的 URL 相同。

与其尝试通过这些委托方法检索 URL,您可以只存储您创建的初始 URL,或者只是确保您可以可靠地重新创建它。