sou*_*rav 1 text-to-speech ios swift
我正在使用AVSpeechSynthesizer发出一些文本数据的声音,它将首次使用,但此后则无法使用。
我得到以下消息。
错误:-
AppName [859:101035] [AXTTSCommon]无法启动音频队列alp!2018-10-26 18:06:53.253536 + 0530 AppName [859:101035] [AXTTSCommon] _BeginSpeaking:无法开始播放
下面我分享我的代码。
let synth = AVSpeechSynthesizer()
fileprivate func speakText(voiceOutdata: String )
{
let utterance = AVSpeechUtterance(string: voiceOutdata)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
synth.speak(utterance)
}
Run Code Online (Sandbox Code Playgroud)
您需要设置AVAudioSession来执行此类任务。这是我的工作代码。希望这可以帮助。
func speakText(voiceOutdata: String ) {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, mode: .default, options: .defaultToSpeaker)
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
} catch {
print("audioSession properties weren't set because of an error.")
}
let utterance = AVSpeechUtterance(string: voiceOutdata)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
let synth = AVSpeechSynthesizer()
synth.speak(utterance)
defer {
disableAVSession()
}
}
private func disableAVSession() {
do {
try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
} catch {
print("audioSession properties weren't disable.")
}
}
Run Code Online (Sandbox Code Playgroud)