swift - AVSpeechSynthesizer isSpeaking 在 Swift 中不起作用

标签 swift swiftui avspeechsynthesizer

所以在更新到 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/

相关文章:

swift - 添加手势识别器 uivew 导航栏 swift 不工作

ios - 使用 URL 在 Swift 中显示电话号码的所有系统选项

ios - AVSpeechSynthesizer 改变声音

ios - 使用 UIAccessibility 读取 HTML 选择

speech-synthesis - 为什么我无法使用 slider 值控制 Apple macOS Speech Synthesis 音频单元?

ios - UIImageJPEGRepresentation 增加 UIImage 大小

ios - 使用谓词从数组中获取无序数据

arrays - Swift 4 - 如何从数组中返回重复值的计数?

ios - 如何在 SwiftUI 中获取 WidgetKit 的圆角半径的大小?

ios - 在 SwiftUI 中切换 View 后 Firebase 图像为空