gpt4 book ai didi

swift - AVSpeechSynthesizer isSpeaking 在 Swift 中不起作用

转载 作者:行者123 更新时间:2023-12-04 17:24:53 32 4
gpt4 key购买 nike

所以在更新到 Xcode 12.0.1 之后,AVSpeechSynthesizer 现在正在模拟器上工作(它已经有一段时间没有为我工作了)。现在,无论合成器是否在说话,isSpeaking 变量始终为假。我想根据合成器是否在说话来触发我的 View 变化。下面的简单版本,有什么想法吗?

import SwiftUI
import AVFoundation

struct ContentView: View {

var synthesizer = AVSpeechSynthesizer()
var utterance = AVSpeechUtterance(string: "Hello World")

var body: some View {
VStack {
Text(synthesizer.isSpeaking ? "Speaking" : "Not Speaking")
Button(action: {synthesizer.speak(utterance)}) {
Text("Speak To Me")
}
}
}
}

最佳答案

它只是没有在您的情况下更新,因为 synthesiser.isSpeaking对于 SwiftUI 是不可观察的。您必须使用 View 模型类和委托(delegate)回调来处理此状态更改
这是初始演示(您可以自己添加停止/暂停/继续操作)

class SpeachViewModel: NSObject, ObservableObject, AVSpeechSynthesizerDelegate {
@Published var isSpeaking = false

private var synthesizer = AVSpeechSynthesizer()
override init() {
super.init()
synthesizer.delegate = self
}

deinit {
synthesizer.delegate = nil
}

func speak(_ utterance: AVSpeechUtterance) {
self.synthesizer.speak(utterance)
}

// MARK: AVSpeechSynthesizerDelegate
internal func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
self.isSpeaking = true
}

internal func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
self.isSpeaking = false
}

internal func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didPause utterance: AVSpeechUtterance) {
self.isSpeaking = false
}

internal func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
self.isSpeaking = false
}

internal func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didContinue utterance: AVSpeechUtterance) {
self.isSpeaking = true
}
}

struct ContentView: View {

@ObservedObject var vm = SpeachViewModel()
var utterance = AVSpeechUtterance(string: "Hello World")

var body: some View {
VStack {
Text(vm.isSpeaking ? "Speaking" : "Not Speaking")
Button(action: {vm.speak(utterance)}) {
Text("Speak To Me")
}
}
}
}

关于swift - AVSpeechSynthesizer isSpeaking 在 Swift 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64109503/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com