Swift 如何停止当前 运行 AVSpeechSynthesizer 的语音输出

Swift How to stop current running Voice Output of AVSpeechSynthesizer

在我的应用程序中,我有一个行为可能会发生 2 个 AVSpeech 合成器同时播放,因此会重叠。这种情况下,有没有办法一开始有新的语音输出就取消当前正在播放的所有语音输出呢?非常感谢! 这是我的代码:

    func makeVoiceOutput(_ text: String) {
    let spech = AVSpeechUtterance(string: text)
    spech.voice = AVSpeechSynthesisVoice(language: Locale.current.languageCode)
    
    let synth = AVSpeechSynthesizer()
    synth.speak(spech)
}

AVSpeechSynthesizer 文档 https://developer.apple.com/documentation/avfaudio/avspeechsynthesizer/ 说:

If the synthesizer is speaking, the synthesizer adds utterances to a queue and speaks them in the order it receives them.

所以你应该将你的语音文本添加到你创建一次的 AVSpeechSynthesizer 实例中,而不是每次都在你的函数中创建一个新的实例。这应该会导致语音文本一个接一个地排队。

或者使用 isSpeakingstopSpeaking 您也可以停止当前的语音输出。

struct ContentView: View {
    
    let synth = AVSpeechSynthesizer() // create once

    @State private var input = ""
    
    var body: some View {
        Form {
            TextField("Text", text: $input)
            Button("Speak") {
                makeVoiceOutput(input)
            }
            Button("Stop") {
                stopVoiceOutput()
            }
        }
    }
    
    func makeVoiceOutput(_ text: String) {
        let spech = AVSpeechUtterance(string: text)
        spech.voice = AVSpeechSynthesisVoice(language: Locale.current.languageCode)
//        let synth = AVSpeechSynthesizer()
        synth.speak(spech)
    }
    
    func stopVoiceOutput() {
        synth.stopSpeaking(at: .immediate)
    }
}