1

I have an array of string and I want to convert it to speech but the problem was it speak all the worlds at once and it isn't clear the array is speechToTextLabels

   @objc func startSpeech()
   {
       for label in speechToTextLabels {
        let utTerance = AVSpeechUtterance(string: label)
        utTerance.voice = AVSpeechSynthesisVoice(language: "en-gb")
        let synthesizer = AVSpeechSynthesizer()
       DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
                       synthesizer.speak(utTerance)
        
       }
        
       }
      
   }

}
La Brewers
  • 39
  • 4
  • The problem is that your loop launches all of the speech simultaneously. You need to wait until each utterance has finished before starting the next one. – matt Jun 20 '21 at 01:54

1 Answers1

0

The code inside for loops execute pretty much instantly - it doesn't wait for one iteration to finish between starting the next. As a result, the synthesizer is speaking all the words at the same time.

Instead, just reduce the array of words into a single String and have the synthesizer speak that.

@objc func startSpeech() {
    let speechToTextLabels = ["Hi", "Hello"]
    let joinedLabel = speechToTextLabels.joined(separator: " ")
    
    let utterance = AVSpeechUtterance(string: joinedLabel)
    utterance.voice = AVSpeechSynthesisVoice(language: "en-gb")
    let synthesizer = AVSpeechSynthesizer()
    DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
        synthesizer.speak(utterance)
    }
}
aheze
  • 24,434
  • 8
  • 68
  • 125