A Few Minutes Of Code
A Few Minutes Of Code

    Getting to know the many voices in your browser

    July 03, 2019

    Video Blogger

    image from undraw.co

    The Speech Synthesis API has been around since about 2014 but still has not gained a huge amount of traction on many sites.

    In a nutshell the api allows you to speak to the user in one of the voices on their browser. To get it working see the below. (this examples also uses react but it is not required.)

    Get The voices in the current browser.

    const voices = window.speechSynthesis.getVoices();

    Now you have access to them you can log out the name and language.

    {voices.map((voice,index) => <li key={index}>{voice.name} - {voice.lang}</li>)}

    Now you have a list of names you can then use them to speak.

    For this we will create a function were we can pass in the voice and return some text that says Hi My Name is (their name).

    const playVoice = voice => {
      let msg = new SpeechSynthesisUtterance();
      msg.voice = voice
      msg.lang = voice.lang
      msg.text = `Hi My Name is ${voice.name}`
      return speechSynthesis.speak(msg);

    Then we will update our link to call our playVoice on click

    {voices.map((voice, index) => (
    <li onClick={() => playVoice(voice)} key={index}>
      {voice.name} - {voice.lang}

    Now each item we click on will play the voice.

    View Code on codesandbox.io

    Previous Create a Cricket Points Table in Javascript - Part 1Next Create a weather voice assistant in React