Introducing audio voices!

Playing with speechSynthesis and learning ES6 along the way!

by Vico Bertogli III

SCSS

body {
  font-size:14px;
  line-height:1em;
  font-weight:bold;
  text-align:center;
  background-color:#333;
  color:#fff;
  
  html, & {
    height:100%;
    width:100%;
  }
  
  > div[data-name]:last-child {
    line-height:2em;
    font-size:2em;
    color:#f00;
  } 
  
}

JavaScript

'use strict';

let verifyAudio = () => {
    return (window && window.speechSynthesis && typeof window.speechSynthesis.speak === "function" && typeof SpeechSynthesisUtterance === "function");
};

if (!verifyAudio()) {
    alert("NO Support");
    throw new Error("NO support");
}

let it = 0;
window.speechSynthesis.cancel();
window.speechSynthesis.onvoiceschanged = () => {
    var voices = window.speechSynthesis.getVoices();
    var randomVoice = voices[Math.floor(Math.random() * voices.length)];
    console.log(`
				Here we go	| Meet one voice | Voices total:
				again. One	| at random:     | ${voices.length}.
				more. Round:| ${randomVoice.name}
				${it++}.
				        
				Voice:`, randomVoice);
    var $el = $('body');
    var talk = (voice) => {
        if (voice.lang === "en-US") {
            var speech = new SpeechSynthesisUtterance(Math.random());
            speech.voice = voice;
            speech.onend = () => {
            	console.log(speech);
                $el.append(`<div data-name=${speech.voice.name}>${speech.voice.name}</div>`);
            };
            window.speechSynthesis.speak(speech);
        }
    };

    if (it === 1) {
        voices.forEach(talk);
    }
};