iosswiftswift4text-to-speechspeech-synthesis

iOS - AVSpeechSynthesizer pause and continueSpeaking issue


macOS: Mojave 10.14.4 beta

iOS: 12.2 beta

Xcode: 10.2 beta

I was using AVSpeechSynthesizer but below code does not resuming from where it paused.

// The pause functionality works fine
if (synth.isSpeaking) {
   synth.pauseSpeaking(at: AVSpeechBoundary.word)
}


// But continueSpeaking always starting from the beginning.
if (synth.isPaused) {
   synth.continueSpeaking();
}

How can I continue from where I left? Anything I'm missing?


Solution

  • I implemented the following code to check your problem (testings under Mojave 10.14.4, iOS 12.2, Xcode 10.2.1 and swift 5.0):

    class SpeechSynthesis: UIViewController {
    
        var synthesizer = AVSpeechSynthesizer()
        var playQueue = [AVSpeechUtterance]()
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
    
            for i in 1...10 {
                let stringNb = "number " + String(i) + " of the speech synthesizer."
                let utterance = AVSpeechUtterance(string: stringNb)
                playQueue.append(utterance)
            }
    
            for utterance in playQueue {
                synthesizer.speak(utterance)
            }
        }
    
        @IBAction func pauseButton(_ sender: UIButton) {
    
            if (synthesizer.isSpeaking == true) {
                if (synthesizer.pauseSpeaking(at: .immediate) == true) {
                    print("PAUSE")
                } else {
                    print("P.R.O.B.L.E.M. when pausing.")
                }
            }
        }
    
        @IBAction func resumeButton(_ sender: UIButton) {
    
            if (synthesizer.isPaused == true) {
                if (synthesizer.continueSpeaking() == true) {
                    print("CONTINUE")
                } else {
                    print("P.R.O.B.L.E.M. when resuming.")
                }
            }
        }
    }
    

    I noticed another problem with the boundary .word that doesn't always pause when triggered but when this constraint is changed to .immediate, everything is resuming from where it paused.

    However, when it rarely pauses with the boundary .word, it always resumes from where it paused as well.

    I don't know where your problem comes from but with the configuration mentioned above and this code snippet, the speech synthesizer resumes from where it paused.