Skip to content

Instantly share code, notes, and snippets.

@mapio
Created November 28, 2015 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mapio/b0b525f3ed0a09e24b70 to your computer and use it in GitHub Desktop.
Save mapio/b0b525f3ed0a09e24b70 to your computer and use it in GitHub Desktop.
HTML5 SpeechSynthesis voices sampler
<ul id="voices"></ul>
var country_code = 'en-US';
var message = 'Hello, world!';
var spans = [];
function add_voice_list() {
var list = document.getElementById( 'voices' );
for ( var i = 0; i < voices.length; i++ ) {
var li = document.createElement( 'li' );
li.setAttribute( 'id', 'voice-' + i );
var span = document.createElement( 'span' );
span.innerHTML = voices[ i ].name;
li.appendChild( span );
list.appendChild( li );
spans.push( span );
}
}
function sample_voices() {
var msg = new SpeechSynthesisUtterance( message );
var i = 0;
function speak() {
if ( i > 0 ) spans[ i - 1 ].style.backgroundColor = 'transparent';
spans[ i ].style.backgroundColor = 'yellow';
msg.voice = voices[ i ];
console.log( i, msg.voice.name );
window.speechSynthesis.speak( msg );
}
msg.onend = function( event ) {
if ( ++i < voices.length ) speak();
};
speak();
}
var voices;
window.speechSynthesis.onvoiceschanged = function() {
if ( voices ) return;
voices = window.speechSynthesis.getVoices().filter(
function( voice ) { return voice.lang == country_code; }
);
console.log( voices.length + " voices loaded…" );
add_voice_list();
sample_voices();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment