首页 > 解决方案 > Swift 中没有数据传递时的补全块语法

问题描述

这很简单,但我无法让它工作。

我想在电话说话之前停止录音。没有数据被传递。

let words = "Hello world"
let utt =  AVSpeechUtterance(string:words)
stopRecordingWithCompletion() {
    voice.speak(utt) 
}

func stopRecordinWithCompletion(closure: () -> Void) {
   recognitionRequest?.endAudio()
    recognitionRequest = nil
    recognitionTask?.cancel()
    recognitionTask = nil      
    let inputNode = audioEngine.inputNode
    let bus = 0
    inputNode?.removeTap(onBus: bus)
    self.audioEngine.stop()
    closure()
}

我究竟做错了什么?

标签: iosswiftclosures

解决方案


您当前的方法对此并不理想。

首先,AVSpeechSynthesizer提供了一个委托,您可以监控更改,包括它何时要说话。

speechSynthesizer(_:willSpeakRangeOfSpeechString:utterance:)

只需观察这一点,然后调用您的停止功能。不需要闭包,因为它是一个同步函数调用。

总之:

  1. 符合AVSpeechSynthesizerDelegate
  2. 实施speechSynthesizer(_:willSpeakRangeOfSpeechString:utterance:)
  3. 当上面的函数被调用时,让它调用你的stopRecording()函数

委托设置示例:

extension YourClassHere: AVSpeechSynthesizerDelegate {
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer,
                           willSpeakRangeOfSpeechString characterRange: NSRange,
                           utterance: AVSpeechUtterance) {
        stopRecording()
    }
}

推荐阅读