2017-03-06 223 views
0

我需要通過名稱設置SpeechSynthesisUtterance語音,例如「Microsoft Zira Desktop - English(United States)」。按名稱設置SpeechSynthesisUtterance語音

我有讓用戶通過可用語音下拉選擇他們想要的'語音'的代碼。然後將該語音名稱保存在$_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(); 
}; 

代碼的該零件,如我可以設置(和保存/回憶)用戶選擇的音色名稱到會話變量(代碼不示出)。

現在我需要在另一個創建SpeechSynthesisUtterance對象的頁面中使用這些保存的值(聲音)。但是無法設置該對象的「聲音」。

到目前爲止:

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

如何設置`通過它的名字speechMessage.voice,如「微軟桌面濟拉 - 英語(美國)」?

+0

語音根據文檔:_this應設置爲SpeechSynthesisVoice的一個對象由[SpeechSynthesis.getVoices()](HTTPS返回://開發商。 mozilla.org/en-US/docs/Web/API/SpeechSynthesis/getVoices)_。所以我想調用'getVoices()'並找到名字與你匹配的那個。 –

回答

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]; 
}