Chrome Speech Synthesis with longer texts

前端 未结 12 1204
难免孤独
难免孤独 2020-11-30 19:48

I am getting a problem when trying to use Speech Synthesis API in Chrome 33. It works perfectly with a shorter text, but if I try longer text, it just stops in the middle. A

12条回答
  •  攒了一身酷
    2020-11-30 20:06

    Yes, the google synthesis api will stop at some point during speaking a long text.

    We can see onend event, onpause and onerror event of SpeechSynthesisUtterance won't be fired normally when the sudden stop happens, so does the speechSynthesis onerror event.

    After several trials, found speechSynthesis.paused is working, and speechSynthesis.resume() can help resume the speaking.

    Hence we just need to have a timer to check the pause status during the speaking, and calling speechSynthesis.resume() to continue. The interval should be small enough to prevent glitch when continuing the speak.

    let timer = null;
    let reading = false;
    
    let readText = function(text) {
    
        if (!reading) {
            speechSynthesis.cancel();
            if (timer) {
                clearInterval(timer);
            }
            let msg = new SpeechSynthesisUtterance();
            let voices = window.speechSynthesis.getVoices();
            msg.voice = voices[82];
            msg.voiceURI = 'native';
            msg.volume = 1; // 0 to 1
            msg.rate = 1.0; // 0.1 to 10
            msg.pitch = 1; //0 to 2
            msg.text = text;
            msg.lang = 'zh-TW';
    
            msg.onerror = function(e) {
                speechSynthesis.cancel();
                reading = false;
                clearInterval(timer);
            };
    
            msg.onpause = function(e) {
                console.log('onpause in ' + e.elapsedTime + ' seconds.');
            }            
    
            msg.onend = function(e) {
                console.log('onend in ' + e.elapsedTime + ' seconds.');
                reading = false;
                clearInterval(timer);
            };
    
            speechSynthesis.onerror = function(e) {
                console.log('speechSynthesis onerror in ' + e.elapsedTime + ' seconds.');
                speechSynthesis.cancel();
                reading = false;
                clearInterval(timer);
            };
    
            speechSynthesis.speak(msg);
    
            timer = setInterval(function(){
                if (speechSynthesis.paused) {
                    console.log("#continue")
                    speechSynthesis.resume();
                }
    
            }, 100);
    
            reading = true;
    
        }
    }
    

提交回复
热议问题