Anurag Mishra
Anurag Mishra

Reputation: 109

change slider value according to the AVSpeechUtterance in swift

I am using AVSpeechUtterance for reading text and trying to implement a change slider thumb according to text read.

I've tried :-

myUtterance = AVSpeechUtterance(string: idFileText)
myUtterance.rate = 0.3

synth.speak(myUtterance)
synth.continueSpeaking() 

if let intValue = Int(idFileText) {
    self.sliderValue.setValue(Float(intValue), 
                              animated: true)
}

The text reader is doing well but slider value does not change.
Can any one please suggest me the right way to implement slider on text reader.

Upvotes: 1

Views: 522

Answers (1)

staticVoidMan
staticVoidMan

Reputation: 20234

Use AVSpeechSynthesizer's delegate speechSynthesizer(_:willSpeakRangeOfSpeechString:utterance:).
It provides the current character range being spoken.
You can use it to determine the slider position as you should already know the length of the entire text.

A basic example would be:

func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, 
                       willSpeakRangeOfSpeechString characterRange: NSRange, 
                       utterance: AVSpeechUtterance) {
    let progress = Float(characterRange.location + characterRange.length)
                   / Float(utterance.speechString.count)
    print(progress)

    self.sliderValue.setValue(progress, 
                              animated: true)
}

For the above logic, ensure your slider object min-max range is 0-1.
And ofcourse, you will need to improve on it to obtain a smoother progress.


Don't forget:

synth.delegate = self

Upvotes: 2

Related Questions