AVAudioInputNode 权限

AVAudioInputNode permission

这似乎是一个非常基本的问题,但我正在努力寻找答案。据我所知,AVAudioInputNode 从 iOS 8 开始可用,例如,它可用于从 iPhone 上的麦克风录音。

我以前知道我会使用 AVAudioRecorderSession 请求权限来记录和检查我是否有权限等。我正在努力了解如何在使用 AVAudioEngine 时请求和检查权限。

所以在类似下面的情况下,我将如何着手做这件事?

import AVFoundation

class ViewController: UIViewController {
    let audioEngine = AVAudioEngine()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func recordPressed(sender:AnyObject) {
        try! startRecording()
    }

    func startRecording() throws{
        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setMode(AVAudioSessionModeMeasurement)
        try audioSession.setActive(true, withOptions: .NotifyOthersOnDeactivation)

        guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") }

        let recordingFormat = inputNode.outputFormatForBus(0)

        inputNode.installTapOnBus(0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in

        }

        audioEngine.prepare()

        try audioEngine.start()


    }

}

我注意到可以在 plist 中设置麦克风隐私消息,调用 audioEngine.inputNode 似乎会显示此消息。但我仍然看不到在哪里检查是否已授予该权限。如果我添加

   if (audioSession.recordPermission() == AVAudioSessionRecordPermission.granted){

    }else{
        print("No permission")
    }

直接在 guard let inputNode 行之后显示消息,但总是告诉我在我响应警报之前未授予权限。

解决此问题的最佳方法是什么?我应该先回到使用 audioSession 方法吗?对于它的价值,其中很多是从围绕 speechRecognizer 的 WWDC 代码中提取的。我只是看不到他们在哪里处理麦克风权限

事实上,它似乎并不总是显示请求权限的警报。我在这里遗漏了什么,因为我发现的示例似乎跳过了这个许可步骤

好的,查看文档我发现了这个:

Recording audio requires explicit permission from the user. The first time your app’s audio session attempts to use an audio input route while using a category that enables recording, the system automatically prompts the user for permission. You can explicitly ask earlier by calling this method. Until the user grants your app permission to record, your app can record only silence.

This method always returns immediately, but the response block awaits user input if the user has not previously granted or denied permission to record in your app.

When a user responds to a recording permission prompt for your app, the system remembers the choice. If the user has denied recording permission, they can reenable it in Settings > Privacy > Microphone.

所以它看起来像是在第一次尝试使用麦克风时自动执行的,但理想情况下我应该事先征得此许可