Niklas
Niklas

Reputation: 75

How to know if text to speech task has finished in swift

I have a loop that parse a text string. Unless a line starts with "<" the line is read with text to speech.

        for i in text {

            switch i.characters.first {

            case "<"? :

                print("<")

            default:

                readText(String(i))

                sleep(5)

            }

        }

Some of the lines spoken are short and others long. I don't want to start reading a line unless the one before has finished. How can I detect when a line is finished reading?

Upvotes: 0

Views: 1592

Answers (1)

Andrej
Andrej

Reputation: 7426

You should use AVSpeechSynthesizerDelegate.

1: set your delegate in viewDidLoad()

let synthesizer = AVSpeechSynthesizer()
synthesizer.delegate = self

2: extend your view controller to conform to the AVSpeechSynthesizerDelegate protocol and implement the speechSynthesizer(_:didFinish:) method

extension MyViewController: AVSpeechSynthesizerDelegate {

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

}

Upvotes: 4

Related Questions