首页 > 解决方案 > 无法为 AVAudioSession 设置类别

问题描述

尝试使用 录制音频AVAudioSession。但无法设置类别最终会导致模棱两可而没有上下文错误。

我正在使用 swift 4。

@objc func setupRecorder() {
    recordingSession = AVAudioSession.sharedInstance()

    do {
        try recordingSession?.setCategory(.playAndRecord, mode: .default)
        try recordingSession.setActive(true)
        recordingSession.requestRecordPermission() { [unowned self] allowed in
            DispatchQueue.main.async {
                if allowed {
                    self.startRecording()
                } else {
                    // failed to record!
                }
            }
        }
    } catch {
        // failed to record!
    }
}

在此处输入图像描述

标签: iosswiftavaudiosessionavaudiorecorder

解决方案


如果您使用的是“Swift4”,那么设置类别的方法是不同的,即

AVAudioSession.sharedInstance().setCategory(String, mode: String, options: AVAudioSessionCategoryOptions)

广告您可以通过以下方式使用它:

try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeDefault, options: AVAudioSessionPortBuiltInSpeaker)

推荐阅读