Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active February 10, 2023 22:48
Show Gist options
  • Select an option

  • Save lewdev/2f28dd7049ee6056e87c98fce1b2ca14 to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/2f28dd7049ee6056e87c98fce1b2ca14 to your computer and use it in GitHub Desktop.
πŸ—£ Speech Synthesis in Japanese
<p id=o></p>
<script>
/*
Sources:
* https://manu.ninja/using-the-speech-synthesis-interface-of-the-web-speech-api/
* https://css-tricks.com/using-the-web-speech-api-for-multilingual-translations/
* https://www.zeolearn.com/magazine/the-new-speech-synthesis-web-api
*/
let syn = speechSynthesis;
o.innerHTML = syn.getVoices().map(v => `<div>${v.name} (${v.lang})</div>`).join``;
let voice;
let attempts = 0;
const initJpVoice = () => {
attempts++;
voice = syn.getVoices().find(_voice => /ja[-_]JP/.test(_voice.lang));
if (!voice) {
if (attempts < 10) setTimeout(() => initJpVoice(), 250);
else alert('`ja-JP` voice not found.');
}
};
initJpVoice();
const speak = s => {
if (!voice || !syn || syn.speaking) return;
const utter = new SpeechSynthesisUtterance(s);
utter.voice = voice;
syn.speak(utter);
};
speak("あ");
// speak("い");
// speak("う");
// speak("え");
// speak("お");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment