【问题标题】:How to change voice in Speech Synthesis?如何在语音合成中改变声音?
【发布时间】:2017-07-30 09:26:36
【问题描述】:

我正在尝试使用Speechsynthesis 的简单示例。

<script>

voices = window.speechSynthesis.getVoices()
var utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[4];
utterance.lang = voices[4].lang;
window.speechSynthesis.speak(utterance);

</script>

但这给出了声音未定义的错误。我发现 getVoices() 是异步加载的。我看到this 的回答并更新了我的代码,如下所示以使用回调。

<script>
window.speechSynthesis.onvoiceschanged = function() {
voices = window.speechSynthesis.getVoices()
var utterance = new SpeechSynthesisUtterance("Hello World");
utterance.voice = voices[4];
utterance.lang = voices[4].lang;
window.speechSynthesis.speak(utterance);
};
</script>

但是由于一些奇怪的原因,文本被说了三遍而不是一遍。如何修复此代码?

【问题讨论】:

    标签: javascript text-to-speech speech-synthesis


    【解决方案1】:

    我无法复制您的问题,但请尝试添加一个事件侦听器,以便您的函数在声音加载后运行。

    let voices, utterance;
    
    function speakVoice() {
    voices = this.getVoices();
    utterance = new SpeechSynthesisUtterance("Hello World");
    utterance.voice = voices[1];
    speechSynthesis.speak(utterance);
    };
    
    speechSynthesis.addEventListener('voiceschanged', speakVoice);
    

    【讨论】:

    • 是否可以为将要创建的所有话语设置声音?还是需要为每个话语定义?
    • @user1063287 您可能只创建一个话语,设置语音对象并在每次说话之前不断更新话语文本:let utt = new window.SpeechSynthesisUtterance(); utt.voice = voices[2]; utt.text = 'say this'; speechSynthesis.speak(utt);
    【解决方案2】:

    这可以在许多 JS Bin 类型的演示中看到。例如:

    http://jsbin.com/sazuca/1/edit?html,css,js,output

    https://codepen.io/matt-west/pen/wGzuJ

    当使用非本地语音时,在使用 voiceschanged 事件的 Chrome 中可以看到此行为。另一个影响是声音列表通常是一式三份的。

    W3C 规范说:

    voiceschanged 事件

    当内容的内容触发 SpeechSynthesisVoiceList,getVoices 方法将返回,有 改变了。示例包括:列表所在的服务器端综合 异步确定,或当客户端语音 已安装/卸载

    ...所以我假设当 Chrome 获取声音时该事件被触发一次,然后在使用第一个非本地声音时触发两次。

    鉴于似乎没有办法区分哪个更改触发了事件,我一直在使用这段丑陋的代码:

        // Add voices to dropdown list
        loadVoices();
        // For browsers that use voiceschanged event
        speechSynthesis.onvoiceschanged = function(e) {
            // Load the voices into the dropdown
            loadVoices();
            // Don't add more options when voiceschanged again
            speechSynthesis.onvoiceschanged = null;
        }
    

    其中 loadVoices() 是将声音添加到选择选项的函数。这并不理想,但它确实适用于所有浏览器(带有语音合成),无论它们是否使用 onvoiceschanged。

    【讨论】:

      【解决方案3】:

      您可以简单地添加此代码并在您的项目中使用 SpeechSynthesis,它适用于我。

      var su;
      
      su = new SpeechSynthesisUtterance();
      
      su.text = "Hello World";
      
      speechSynthesis.speak(su);
      
      speechSynthesis.cancel();
      

      【讨论】:

      • 他在问如何改变声音
      猜你喜欢
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      相关资源
      最近更新 更多