1
votes

I need to set the SpeechSynthesisUtterance voice by it's name, such as "Microsoft Zira Desktop - English (United States)".

I have code that will let the user select their desired 'voice' via a dropdown of available voices. That voice name is then saved in a PHP session variable (and cookie) in $_SESSION[voicesettings][voice] so that the user will get their desired voice the next visit.

Here is an extract of the code used:

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();
};

This part of the code works, as I can set (and save/recall) the user-selected voice name into the Session variable (code not shown).

Now I need to use those saved values (the voice) in another page that creates the SpeechSynthesisUtterance object. But having trouble setting the 'voice' of that object.

So far:

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

How do I set the `speechMessage.voice by it's name, such as "Microsoft Zira Desktop - English (United States)" ?

1
According to the docs: This should be set to one of the SpeechSynthesisVoice objects returned by SpeechSynthesis.getVoices(). So I guess call getVoices() and find the one whose name matches yours. - Johnny Mopp

1 Answers

0
votes

You can find voice by name with code below

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