Writing TextToSpeech in Browser Using Async Function

2023-05-03 11:47 (1 years ago) ytyng

Here's the English translation of the provided Japanese blog article:


This code uses the await keyword with the speech method of SpeechSynthesisUtterance. It performs the text-to-speech processing in a synchronous manner in a web browser.

However, please note that due to browser security reasons, you cannot make it automatically speak as soon as the browser is opened. The user must click a button or perform some action on the page at least once for the speech synthesis to work.

function asyncSpeak(text) {
  const ssu = new SpeechSynthesisUtterance();
  ssu.text = text;
  ssu.lang = 'en-US';
  speechSynthesis.speak(ssu);
  return new Promise((resolve, reject) => {
    ssu.onend = () => {
      resolve();
    };
  });
}

async function onStarted() {
  await asyncSpeak('one two three four five six seven eight nine ten');
  console.log('end');
}

Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011