A Pen by Massimo Santini on CodePen.
Created
November 28, 2015 20:36
-
-
Save mapio/b0b525f3ed0a09e24b70 to your computer and use it in GitHub Desktop.
HTML5 SpeechSynthesis voices sampler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ul id="voices"></ul> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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