从 SFSpeechRecognizer 发布和使用转录本

Publishing and Consuming a transcript from SFSpeechRecognizer

我在 SFSpeechRecognizer 周围使用 Apple 的 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 { [=11=] as! String? ?? "" }
            .sink(receiveCompletion: {
                print ([=11=]) },
                  receiveValue: {
                    self.SpeechText = [=11=]
                    self.doStuff(transcript: [=11=])
                  })
    }

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

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

如何进行这项工作?

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

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 { [=10=] as! String? ?? "" }
            .sink(receiveCompletion: {
                print ([=10=]) },
                  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

测试