为什么使用 SpeechRecognizer 时 SpeechSynthesizer 不起作用?

问题描述 投票:0回答:1

这显然是其他几篇文章的重复,但它们都已经有好几年了,而且他们的解决方案都不适合我。

我正在使用 SpeechSynthesizer 和 SpeechRecognizer。识别任务完成后,SpeechSynthesizer 停止产生声音输出。

我正在 Xcode 15.2 中使用最新的 SwiftUI,部署到运行 iOS 17.3.1 的 iPhone 14 Pro。

一些相关帖子是:

使用SFSpeechRecognizer后AVSpeechSynthesizer不说话

iOS:使用 SFSpeechRecognizer 录制后 AVSpeechSynthesizer 无法工作

这是我的 SpeechSynthesizer 函数:

func speak(_ text: String) {
    let utterance = AVSpeechUtterance(string: text)
    utterance.voice = AVSpeechSynthesisVoice(identifier: self.appState.chatParameters.voiceIdentifer)
    utterance.rate = 0.5
    speechSynthesizer.speak(utterance)
}

这是设置 SpeechRecognizer 的代码(借自 https://www.linkedin.com/pulse/transcribing-audio-text-swiftui-muhammad-asad-chattha):

private static func prepareEngine() throws -> (AVAudioEngine, SFSpeechAudioBufferRecognitionRequest) {
    print("prepareEngine()")
    let audioEngine = AVAudioEngine()
   
    let request = SFSpeechAudioBufferRecognitionRequest()
    request.shouldReportPartialResults = false
    request.requiresOnDeviceRecognition = true

    let audioSession = AVAudioSession.sharedInstance()
    try audioSession.setCategory(.playAndRecord)
    try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
    let inputNode = audioEngine.inputNode
   
    let recordingFormat = inputNode.outputFormat(forBus: 0)
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) {
        (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
        request.append(buffer)
    }
    audioEngine.prepare()
    try audioEngine.start()
   
    return (audioEngine, request)
}

只要我不调用prepareEngine(),SpeechSynthesizer 就可以正常工作。

预先感谢您的帮助。

ios swiftui text-to-speech speech-to-text
1个回答
0
投票

以下内容适用于我的实际设备。在 UIKit 中,您必须有一个

AVSpeechSynthesizer
的类变量。在 SwiftUI 中似乎也是如此。

import SwiftUI
import AVFoundation

struct ContentView: View {
    @State var synthesizer = AVSpeechSynthesizer()
    var body: some View {
        VStack {
            Button("Speak") {
                speak(text: "Hello, world!")
            }
        }
    }
    
    func speak(text: String) {
        let utterrance = AVSpeechUtterance(string: text)
        synthesizer.speak(utterrance)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.