代码之家  ›  专栏  ›  技术社区  ›  Nirojan Selvanathan

谷歌chrome语音合成中的女声

  •  2
  • Nirojan Selvanathan  · 技术社区  · 7 年前

    我在这两个场景中都使用了这段代码。

            var msg = new SpeechSynthesisUtterance();
            var voices = window.speechSynthesis.getVoices();
            msg.voice = voices[1];
            msg.text = "hello world";
            msg.lang = 'en-US';
            speechSynthesis.speak(msg);
    

    1 回复  |  直到 7 年前
        1
  •  6
  •   Nirojan Selvanathan    7 年前

    找到了根本原因。 Getting the list of voices in speechSynthesis of Chrome (Web Speech API)

    调用是异步的,所以当我尝试在索引中运行时。html语音数组为空。正如我建议的那样,当我运行这个,然后使用speak时,它工作得很好。

        var msg;
        var voices;
        var timer = setInterval(function() {
            voices = speechSynthesis.getVoices();
            console.log(voices);
            if (voices.length !== 0) {
                msg = new SpeechSynthesisUtterance();
                msg.voice = voices[0];
                speechSynthesis.speak(msg);
                msg.lang = 'en-US';
                clearInterval(timer);
            }
        }, 200);
        timer();
        speechSynthesis.speak("hello world");