NSSpeechSynthesizer startSpeakingString:toURL: doesn't work on long texts

I have found one weird problem, it would be helpful if someone knows something about it or at least if someone could test it.


Previously (not sure how much time before, but surely in 2017) NSSpeechSynthesizer startSpeakingString:toURL: could handle the text of any length (as long as there was enough disk space). Right now if I use some shorter text it still works, but if I use longer texts like Alice's adventures in Wonderland (for the testing you can get it at this link: http://www.gutenberg.org/ebooks/28885.txt.utf-8 ) it simply never completes.


So is this some general problem? Is it just my Mac? How to repair it then?

Replies

An utterance can control speech parameters, you can split text into sections, create an utterance with each section and call speak for each utterance in the SpeechSynthesizer.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var synthesizer : AVSpeechSynthesizer!
    
    
    func speak(utterance: AVSpeechUtterance){
        print("\(type(of: self)) \(#function)")
        synthesizer.speak(utterance)
    }
    
    func utteranceWith(_ string: String) -> AVSpeechUtterance{
        let utterance = AVSpeechUtterance(string: string)
        utterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
        return utterance
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        synthesizer = AVSpeechSynthesizer()
        synthesizer.pauseSpeaking(at: .word)
        
        guard let filepath = Bundle.main.path(forResource: "book", ofType: "txt") else { fatalError("Can not get filepath") }
        
        
        do {
            let contents = try String(contentsOfFile: filepath)
            let paragraphs = contents.components(separatedBy: "\n")
            for phrase in paragraphs {
                speak(utterance:utteranceWith(phrase))
            }
        }
        catch {
            print("Contents could not be loaded.")
        }
    }
}