AVSpeechSynthesizer在停止说话后在话语结束时启动



AVSpeechSynthesizer工作得很好,如果我不试图阻止它。在停止和重新开始之后,下一个话语从上一个结束的地方开始。例如"你好,世界";和"你好,地球"。当我在"你好"之后停止第一个单词时,下一个单词就会像"地球"一样出现。想要我想要是完整的句子。所以:

实际:

  • "Hello"——停止
  • "Earth">

我想要的:

  • "Hello"——停止
  • "你好Earth">

.

class TextToSpeechService: NSObject, AVSpeechSynthesizerDelegate {

let synthesizer: AVSpeechSynthesizer = AVSpeechSynthesizer()
var wasStopped: Bool = false

init () {
super.init()
self.synthesizer.delegate = self
}

public func start (text: String, completion: @escaping (Result<Void, TextToSpeechError>) -> Void) {
self.setAudioPreferences()
self.wasStopped = false

let hasLanguage = AVSpeechSynthesisVoice.speechVoices().first(where: { $0.language == "de-DE" }) != nil
if (hasLanguage) {
let utterance = AVSpeechUtterance(string: text)

utterance.voice = AVSpeechSynthesisVoice(identifier: "com.apple.ttsbundle.siri_Helena_de-DE_compact")

self.synthesizer.speak(utterance)
} else {
print("LANGUAGE NOT AVAILABLE")
}
}

public func stop () {
self.wasStopped = true
self.synthesizer.stopSpeaking(at: .immediate)
}

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
if !wasStopped {
print("success speaking")
}
}

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
if !wasStopped {
print("success speaking")
}
}

func setAudioPreferences () {
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSession.Category.playback, options: [.defaultToSpeaker, .allowBluetooth, .allowBluetoothA2DP])
} catch let error {
print("audioSession properties weren't set. Error: (error.localizedDescription)")
}
}
}

调用(缩短)

let textToSpeechService = TextToSpeechService()
textToSpeechService.start(text: "Hello World")
// after word "Hello"
textToSpeechService.stop()
textToSpeechService.start(text: "Hello Earth")

是否可以重置语音合成器?

我有同样的问题…
现在你可以使用"hack"-更改停止方法如下:

public func stop () {
self.wasStopped = true
self.synthesizer.stopSpeaking(at: .immediate)
let utterance = AVSpeechUtterance(string: "")
self.synthesizer.speak(utterance)
self.synthesizer.stopSpeaking(at: .immediate)
}

文本转语音服务只是问题的一部分。我也有一个语音识别器,我总是设置音频偏好。

错🚫

TTS:

try session.setCategory(AVAudioSession.Category.playback, options: [.defaultToSpeaker, .allowBluetooth, .allowBluetoothA2DP])

STT:

try session.setCategory(AVAudioSession.Category.record, options: [.defaultToSpeaker, .allowBluetooth, .allowBluetoothA2DP])

现在,我只在init上这样做一次,并且对两个都这样做:

try session.setCategory(AVAudioSession.Category.playAndRecord, options: [.defaultToSpeaker, .allowBluetooth, .allowBluetoothA2DP])

最新更新