Search code examples
javascriptwebspeech-api

Chinese text plays once with Web Speech API, but not a second time


So I am using a modified script to try to play some text from the Web Speech API.

The code was originally here:

Chrome Speech Synthesis with longer texts

Here's my modified variant:

function googleSpeech(text, rate) {
    if (!reading) {
        speechSynthesis.cancel();
        if (timer) {
            clearInterval(timer);
        }
        let msg = new SpeechSynthesisUtterance();
        let voices = window.speechSynthesis.getVoices();
        msg.voice = voices[63];
        msg.voiceURI = 'native';
        msg.volume = 1; // 0 to 1
        msg.rate = rate; // 0.1 to 10
        msg.pitch = 1; //0 to 2
        msg.text = text;
        msg.lang = 'zh-CN';

        msg.onerror = function (e) {
            speechSynthesis.cancel();
            reading = false;
            clearInterval(timer);
        };

        msg.onpause = function (e) {
        };

        msg.onboundary = function (event) {
        };

        msg.onend = function (e) {
            speechSynthesis.cancel();
            reading = false;
            clearInterval(timer);
        };

        speechSynthesis.onerror = function (e) {
            speechSynthesis.cancel();
            reading = false;
            clearInterval(timer);
        };

        console.log(msg);
        speechSynthesis.speak(msg);

        timer = setInterval(function () {
            if (speechSynthesis.paused) {
                speechSynthesis.resume();
            }

        }, 100);

        reading = true;
    }

}

I am able to get this to play ONCE. Whenever I try to get it to play again, it doesn't work - this is despite running speechSynthesis.cancel();. When I reload the page, everything works fine again - for one playback.

Is there any consistent way to play the text again? It seems like this might be related to the many bugs in the Web Speech API. This is on Chrome 68.

Here's a sample of the text I am playing:

我是一个兵。来自老百姓。 打败了日本狗强盗。 消灭了蒋匪军。

Solution

  • The answer actually turned out to be related to the value of the rate property.

    While the official documentation for the Web Speech API says that it supports a value of .1 to 10 for rate, it appears that Chrome (at least Chrome 68, the version I am running) does not fully support a rate outside of the range of .5 to 2.

    Anything outside this range causes sound dispersion and breaks after one use of the API and the sound will not work anymore until page refresh.