在我的應用程式中,我的行為可能會發生 2 個 AVSpeech 合成器同時播放,因此會重疊。在這種情況下,有沒有辦法在新的語音輸出開始后立即取消當前正在播放的所有語音輸出?非常感謝!這是我的代碼:
func makeVoiceOutput(_ text: String) {
let spech = AVSpeechUtterance(string: text)
spech.voice = AVSpeechSynthesisVoice(language: Locale.current.languageCode)
let synth = AVSpeechSynthesizer()
synth.speak(spech)
}
uj5u.com熱心網友回復:
AVSpeechSynthesizer檔案https://developer.apple.com/documentation/avfaudio/avspeechsynthesizer/說:
如果合成器正在說話,則合成器將話語添加到佇列中,并按照接收到的順序說出它們。
因此,您應該將您的語音文本添加到AVSpeechSynthesizer您創建一次的實體中,而不是每次都在您的 func 中創建一個新實體。這應該導致一個接一個地排隊口語文本。
或者使用isSpeaking并且stopSpeaking您也可以停止當前的語音輸出。
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)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443576.html
下一篇:創建環境物件
