▲TOPへ戻る

Web Speech APIのspeechSynthesiを使って、テキストを読み上げる方法 多言語にも対応

Web Speech API speechSynthesi

Web Speech APIのspeechSynthesiを使って、文章を読み上げる方法を紹介します。 読み上げる精度はそれほどではありませんが、十分楽しめると思います。

読み上げるための基本設定

  1. new でインスタンス(speech)を生成
  2. speech.langで言語を指定
  3. speech.textで読み上げる文を指定
  4. speechSynthesis.speak(speech)で読み上げ

これだけで読み上げてくれます。

  <button onclick="speech()">読み上げる</button>

  <script>
    function speech() {
      const speech = new SpeechSynthesisUtterance();
      speech.lang = "en-US";  //言語を指定
      speech.text = "Hello everyone"; //読み上げたい文
      speechSynthesis.speak(speech);
    };
  </script>

textareaの文章を取得し、読み上げる

  <textarea id="text" cols="30" rows="3"></textarea> 
  <button onclick="speech()">読み上げる</button>

  <script>
    const text = document.getElementById("text");

    function speech() {
      const speech = new SpeechSynthesisUtterance();
      speech.lang = "ja-JP";  //今度は日本語に設定
      speech.text = text.value; //textareaの値を代入
      speechSynthesis.speak(speech);
    }
  </script>

言語を選択できるようにする

speechSynthesis.getVoices()

  speechSynthesis.addEventListener("voiceschanged", function () {
    console.log(speechSynthesis.getVoices());
  });

console.logで見てみると、いろいろ取得できていることがわかります。

speechAPI

取得した言語をselectに格納

  <select">
    <option value="">Google US English (en-US)</option>
  </select>
  
  <script>
    const voiceList = document.querySelector(select);
    function voices() {
      for (let i = 0; i < speechSynthesis.getVoices().length; i++) {
        let voice = speechSynthesis.getVoices()[i];
        let selected =
          voice.name === "Google US English" ? "selected" : "";
        const option = document.createElement("option");
        option.value = voice.name;
        if (!selected == null) {
          option.setAttribute(selected, true);
        }
        option.textContent = voice.name + "" + voice.lang + "";
        voiceList.appendChild(option);
      }
    }
    speechSynthesis.addEventListener("voiceschanged", function () {
      voices();
    });
  </script>

多言語で読み上げる

  <textarea id="text" cols="30" rows="3"></textarea><br>
  <select id="lang" style="margin-bottom: 10px;">
    <option value="">Google US English (en-US)</option>
  </select><br>
  <button onclick="speech()">読み上げる</button>

  <script>
    const text = document.getElementById("text");
    const voiceList = document.querySelector("#lang");

    function speech() {
      let speech = new SpeechSynthesisUtterance();
      for (let voice of speechSynthesis.getVoices()) {
        if (voice.name === voiceList.value) {
          speech.voice = voice;
        }
      }
      speech.text = text.value; //読み上げたい単語を代入
      speechSynthesis.speak(speech);
    }
  </script>


まとめ

  1. Web Speech APIのspeechSynthesisを使う。
  2. speechSynthesis.getVoices()で多言語を取得。
  3. speechSynthesis.speak() で読み上げる。

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ