【问题标题】:Publishing and Consuming a transcript from SFSpeechRecognizer从 SFSpeechRecognizer 发布和使用成绩单
【发布时间】:2022-06-16 15:53:50
【问题描述】:

我正在使用 Apple 的 SFSpeechRecognizer 周围的 Observable 包装器示例,如下所示:

class SpeechRecognizer: ObservableObject {
    @Published var transcript: String
    func transcribe() {}
}

我们的目标是使用 ViewModel 在脚本生成时使用它,并将值传递给 SwiftUI 视图以进行可视化调试:

class ViewModel : ObservableObject {
    @Published var SpeechText: String = ""
    @ObservedObject var speech: SpeechRecognizer = SpeechRecognizer()

    public init() {
        speech.transcribe()
        speech.transcript.publisher
            .map { $0 as! String? ?? "" }
            .sink(receiveCompletion: {
                print ($0) },
                  receiveValue: {
                    self.SpeechText = $0
                    self.doStuff(transcript: $0)
                  })
    }

    private void doStuffWithText(transcript: String) {
        //Process the output as commands in the application
    }
}

我可以确认,如果我直接在 SwiftUI 视图中观察 transcript,则数据正在流经。我的问题是接收变化的值,然后将该数据分配给我自己发布的变量。

我该如何进行这项工作?

【问题讨论】:

    标签: swift combine sfspeechrecognizer


    【解决方案1】:

    订阅应该保存,否则会立即取消,并且您需要在实际使用之前进行订阅(以及其他一些与内存相关的修改)。所以我假设你想要这样的东西:

    class ViewModel : ObservableObject {
        @Published var SpeechText: String = ""
        var speech: SpeechRecognizer = SpeechRecognizer()  // << here !!
    
        private var subscription: AnyCancellable? = nil    // << here !!
        public init() {
            self.subscription = speech.transcript.publisher  // << here !!
                .map { $0 as! String? ?? "" }
                .sink(receiveCompletion: {
                    print ($0) },
                      receiveValue: { [weak self] value in
                        self?.SpeechText = value
                        self?.doStuffWithText(transcript: value)
                      })
            self.speech.transcribe()                  // << here !!
        }
    
        private func doStuffWithText(transcript: String) {
            //Process the output as commands in the application
        }
    }
    

    使用 Xcode 13.2 测试

    backup

    【讨论】:

    • 是的,老实说,后来也用另一种方法发现了这一点,并意识到我一直做错了。感谢您的观看!
    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多