【问题标题】:SFSpeechRecognizer crashes if no microphone input attached in Mac osx如果 Mac osx 中没有连接麦克风输入,SFSpeechRecognizer 会崩溃
【发布时间】:2020-08-26 07:20:57
【问题描述】:

我已经在我的 Mac 应用中实现了 Speech to Text。它完美地工作。但是如果 Mac mini 中没有连接输入设备(麦克风),它就会崩溃。下面是我的代码

    let node = audioEngine.inputNode
        
    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
      self.request.append(buffer)
    }

    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        print("There has been an audio engine error.")
        return print(error)
    }
    guard let myRecognizer = SFSpeechRecognizer() else {
        print("Speech recognition is not supported for your current locale.")
        return
    }
    if !myRecognizer.isAvailable {
        print("Speech recognition is not currently available. Check back at a later time.")
        // Recognizer is not available right now
        self.delegate?.speechToTextFailed("Speech recognition is not currently available. Check back at a later time.")
        return
    }
    self.onCheckSupportedSpeechToTextLanguage(kUserDefaults?.value(forKey: kChoosedLang) as! String)
    sttTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (timer) in
        
    })
    recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
        if let result = result {
            
            let bestString = result.bestTranscription.formattedString
            var lastString: String = ""
            for segment in result.bestTranscription.segments {
                let indexTo = bestString.index(bestString.startIndex, offsetBy: segment.substringRange.location)
                lastString = String(bestString[indexTo...])
            }
            print(" bestString : \(bestString)")
            self.delegate?.speechToTextConvertedText(self.previousString, bestString)
            self.previousString = bestString
            
        } else if let error = error {
            print("There has been a speech recognition error.")
            print(error)
            self.delegate?.speechToTextFailed("There has been a speech recognition error.")
        }
    })

如果 macmini 中没有连接耳机,应用程序会在 node.installTap(onBus... 在上面的代码中崩溃。

所以我的问题是如何检测用户是否没有连接麦克风或有问题并停止应用程序崩溃。

【问题讨论】:

    标签: swift macos speech-to-text avaudioengine


    【解决方案1】:

    您可以检查输入设备的通道数。

    if 0 < AVAudioSession.sharedInstance().inputNumberOfChannels {
      // DO Somthing..
    }
    

    如果没有可用的输入设备,该 API 将返回 0。

    【讨论】:

    • 是的,我为 Mac osx 做了一些类似的操作,audioEngine.inputNode.inputFormat(forBus: 0).channelCount,这给了我计数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多