按名称设置SpeechSynthesisUtterance

时间:2017-03-06 21:58:18

标签: text-to-speech

我需要通过它的名称设置SpeechSynthesisUtterance语音,例如" Microsoft Zira Desktop - 英语(美国)"。

我的代码可以让用户选择他们想要的语音'通过下拉可用的声音。然后将该语音名称保存在$_SESSION[voicesettings][voice]中的PHP会话变量(和cookie)中,以便用户在下次访问时获得所需的语音。

以下是所用代码的摘录:

function loadVoices() {
  // Fetch the available voices.
    var voices = speechSynthesis.getVoices();
    var voiceselected = "<?php echo $_SESSION[voicesettings][voice]?>";
  // Loop through each of the voices.
    voices.forEach(function(voice, i) {
    // Create a new option element.
        var option = document.createElement('option');
    // Set the options value and text.
        option.value = voice.name;
        option.innerHTML = voice.name;
        if (voice.name === voiceselected){
            option.selected = true;
    }
    // Add the option to the voice selector.
        voiceSelect.appendChild(option);
    });
}

// Execute loadVoices.
loadVoices();

// Chrome loads voices asynchronously.
window.speechSynthesis.onvoiceschanged = function(e) {
  loadVoices();
};

这部分代码可以正常工作,因为我可以将用户选择的语音名称设置(并保存/调用)到Session变量中(代码未显示)。

现在我需要在另一个创建SpeechSynthesisUtterance对象的页面中使用这些保存的值(语音)。但无法设置“声音”#39;那个对象。

到目前为止:

var speechMessage = new SpeechSynthesisUtterance(msg);
    speechMessage.rate = <?php echo $rate;?>;
    speechMessage.pitch = <?php echo $pitch;?>;
    speechMessage.volume = <?php echo $volume;?>;

如何设置`speechMessage.voice的名称,例如&#34; Microsoft Zira Desktop - 英语(美国)&#34; ?

1 个答案:

答案 0 :(得分:0)

您可以通过名称找到声音,代码如下

var voices = window.speechSynthesis.getVoices();
var foundVoices = voices.filter(function(voice) 
{ 
    return voice.name == 'Microsoft Zira Desktop - English (United States)'; 
});

if(foundVoices.length === 1){
    speechMessage.voice = foundVoices[0];
}