SwiftUI change reading speed

41 Views Asked by At

I need help with a problem I'm having with my SwiftUI project. I have a button created to change the reading speed, but when I press it, the speed changes correctly, but the reading starts from the beginning and I don't understand how to solve it

func startReading() {
        if let document = pdfDocument {
            let pageCount = document.pageCount
            var documentContent = ""
            for pageIndex in 0..<pageCount {
                if let page = document.page(at: pageIndex),
                   let pageContent = page.string {
                    documentContent.append(pageContent)
                }
            }
            
            if synthesizer.isSpeaking {
                synthesizer.stopSpeaking(at: .immediate)
            }
            
            // Assign the utterance to the instance variable
            utterance = AVSpeechUtterance(string: documentContent)
            utterance?.rate = AVSpeechUtteranceMaximumSpeechRate * Float(CGFloat(speeds[speedIndex])) / 2.0
            synthesizer.speak(utterance!)
        }
    }
    
    func increaseSpeed() {
        if synthesizer.isSpeaking {
            synthesizer.stopSpeaking(at: .immediate)
        }
        speedIndex = (speedIndex + 1) % speeds.count
        if isPlaying {
            // Update the rate of the utterance with the new speed
            utterance?.rate = AVSpeechUtteranceMaximumSpeechRate * Float(CGFloat(speeds[speedIndex])) / 2.0
            startReading()
        }
    }

I would like it to change the speed when I press the button but without returning to the beginning, whether it is in play (changing in real time) or if it is paused (when I press Play again the reading resumes from the point where it had started left before pausing it but with the speed changed)

0

There are 0 best solutions below