AVSpeechSynthesizer is not working After use one time
Asked Answered
A

4

6

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)
 }
Arsenious answered 26/10, 2018 at 12:44 Comment(0)
D
14

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.")
    }
}
Dubois answered 5/12, 2018 at 6:28 Comment(1)
can I get same code in Objective-C ??? coz I am also having same issue & my code is in Objective-CForeside
R
1

for me the problem was my speaker volume was off and it was also in the vibration mode

Revenant answered 17/8, 2020 at 11:2 Comment(0)
C
0

try below code:

let synthesizer = AVSpeechSynthesizer()
 fileprivate func speakText(voiceOutdata: String ){
    synthesizer.stopSpeakingAtBoundary(.Immediate)
    let utterance = AVSpeechUtterance(string: voiceOutdata)
    utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
    synthesizer.speakUtterance(utterance)
}
Canella answered 26/10, 2018 at 12:54 Comment(1)
I tried this but it's not working. still getting the same error.Arsenious
H
0

its working for me:

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.")
}
Hadik answered 27/2, 2020 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.