Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

ios - AVSpeechSynthesizer is not working After use one time

I'm using AVSpeechSynthesizer for voice out some text data, it'll work for first time but it didn't work after that.

I'm getting below messages.

Error:-

AppName[859:101035] [AXTTSCommon] Failure starting audio queue alp! 2018-10-26 18:06:53.253536+0530 AppName[859:101035] [AXTTSCommon] _BeginSpeaking: couldn't begin playback

Below i share my code.

 let synth = AVSpeechSynthesizer()

 fileprivate func speakText(voiceOutdata: String )
 {
    let utterance = AVSpeechUtterance(string: voiceOutdata)
    utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
    synth.speak(utterance)
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to set the AVAudioSession for performing such tasks. Here is my working code. Hope this helps.

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.")
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...