繁体   English   中英

iOS AVAudioRecorder.record() 在设备上返回 false

[英]iOS AVAudioRecorder.record() returns false on device

AVAudioRecorder.record()仅在授予带有系统警报的麦克风权限后第一次返回true ,而不是始终返回false 在模拟器.record()总是返回true 如何在第二次和其他应用程序启动时制作 AVAudioRecordenr 记录?

这是代码:

func startRecording() {
        let dirPath =  NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] as String
        let recordName = "record.wav"
        self.audioURL = URL(fileURLWithPath: dirPath + "/" + recordName)
        let session = AVAudioSession.sharedInstance()
        let microPhoneStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)
        print(microPhoneStatus)
            do {
                try session.setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.duckOthers)
            } catch {
                print(error)
            }

            guard let recorder  = try? AVAudioRecorder(url: self.audioURL, settings: [:]) else {
                self.finishRecording(success: false)
                return
            }


            self.audioRecorder = recorder
            self.audioRecorder.isMeteringEnabled = true
            self.audioRecorder.delegate = self
            let prepare = self.audioRecorder.prepareToRecord()
            try! session.setActive(true, options: [])
            let record = self.audioRecorder.record()
    }

已经尝试添加NSMicrophoneUsageDescription并从代码中请求AVAudioSession requestRecordPermission

在录制音频之前需要完成两件重要的事情。

  1. 该应用程序需要声明为什么/如何记录是必要的。 Info.plist添加Privacy - Microphone Usage Description以及良好的文字说明。

  2. 应用程序需要在每次调用AVAudioRecorder.record()之前请求明确的用户许可。 实现类似的东西:

import AVFoundation

let session = AVAudioSession.sharedInstance()
session.setCategory(.playAndRecord, mode: .default)
session.setActive(true)
session.requestRecordPermission { granted in
    print(granted)
}

请注意,这是一个简化的示例。 需要添加额外的 do/try/catch 错误处理,因为这些方法被标记为throws

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM