iosavspeechutterance

Detect ongoing speech from AVSpeech and AVUtterance in Swift


I gather you can use a delegate method to tell when AV speech has finished

 extension MyViewController: AVSpeechSynthesizerDelegate {

    func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) {
            print("speech finished")
        }

    }

But how can you tell if speech is ongoing and has not yet finished?

Right now, I start some speech with

voice.speak(utt)
//do something

I would like to do something while the person is speaking before they finish. Merely putting a line do something below the voice.speak(utt) doesn't seem to work. I think this is due to a race condition. I can't be sure it fires as soon as the voice is triggered and before the delegate method fires after the utterance is complete.

A completion bloc won't help because I want to do something before the utterance is completed. So how can I do something while the utterance is taking place, in other words start doing something at the precise moment the utterance starts?


Solution

  • how can you tell if speech is ongoing...

    Retrieve the boolean value that indicates whether the synthesizer is speaking from the isSpeaking method of your AVSpeechSynthesizer instance.

    ...and has not yet finished?

    Detect the beginning thanks to the didStart method of the AVSpeechSynthesizerDelegate protocol that will provide the concerned utterance.

    Besides, if you want to know exactly the location of the vocalization, use the willSpeakRangeOfSpeechString of the AVSpeechSynthesizerDelegate protocol.

    All these elements should help you to detect ongoing speech from AVSpeech and AVUtterance as desired.