DrDru / drdru.github.io_origin

Japanese learning content targeted to beginners so they can start reading from day 1. It aims to be a Lingua Latina per Se Illustrata for Japanese.
https://drdru.github.io/
37 stars 0 forks source link

Speech synthesis #6

Open MzHub opened 2 years ago

MzHub commented 2 years ago

I saw speech synthesis has been suggested. I realize it would be a lot of work, and that browser extensions may be a better solution.

That said, I wanted to let you know, that the speech synthesis part itself is very simple. I've added this to all my tiny Japanese learning web apps.

let speak;
{
  // Speech synthesis
  const synth = window.speechSynthesis;
  let voices = synth.getVoices();
  speechSynthesis.onvoiceschanged = () => { voices = synth.getVoices() };
  speak = function (text) {
    let selectedVoice;
    for (const voice of voices) {
      if (voice.name.toLowerCase().includes('japan') || voice.lang.toLowerCase().includes('ja-jp')) {
        selectedVoice = voice;
      }
    }
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.voice = selectedVoice;
    utterance.pitch = 1;
    utterance.rate = 1;
    synth.speak(utterance);
  };
}

Usage:

speak('こんにちは');

If you end up using it, you might want to add a check for whether Japanese voice was found, and make it do nothing if not. Currently it will default to whatever is the default voice, which is not nice for a public project.

Either way, cool project! And feel free to ignore this, just wanted to let you know in case it ends up being useful.

EDIT: So something like this:

    let selectedVoice;
    let hasJapaneseVoice = false;
    for (const voice of voices) {
      if (voice.name.toLowerCase().includes('japan') || voice.lang.toLowerCase().includes('ja-jp')) {
        selectedVoice = voice;
        hasJapaneseVoice = true;
        break;
      }
    }
    if ( ! hasJapaneseVoice) {
      return;
    }
DrDru commented 2 years ago

Thanks a lot for the kind word and for the suggestion. I bear that in mind and will play with it. It mind be useful in the future.