LoginSignup
26
23

More than 5 years have passed since last update.

Web Speech API を 利用して 英単語の音声確認をするアプリを作る

Posted at

最近音声認識や音声入力に興味があり、いろいろと調べています。

今回は Web Speech API に含まれる、音声合成APIを利用して、簡単なアプリを作ってみました。

やること

英単語などの発音を教えてくれるアプリ
フォームから英語を入力しボタンを押すと、ブラウザが英語の音声で発音を教えてくれる
Web Speech APIを利用

Web Speech API とは

W3C Community Final Specification Agreement(FSA)の下、Speech API Communityにより策定されている、JavaScript のAPI。

音声認識と、音声合成の2つの機能を持つ。

Speech API Community が公開している仕様文章はこちら。
https://w3c.github.io/speech-api

MDNのリファレンスはこちら。
https://developer.mozilla.org/ja/docs/Web/API/Web_Speech_API

音声合成のAPIは Web Speech Synhtesis API を利用する。

Web Speech Synthesis APIの記述とサンプルコード

SpeechSynthesisUtterance オブジェクトで発声させたい単語・文章を定義できる。

SpeechSynthesisUtterance.text

で、発声させたい単語を定義

SpeechSynthesisUtterance.lang

で、発声する言語を指定

SpeechSynthesisUtterance.lang = 'ja'

なら日本語で発声

SpeechSynthesisUtterance.lang = 'en-US'

なら英語で発声

SpeechSynthesis.speak() メソッドで音声の発生を行う。

https://w3c.github.io/speech-api/#examples-synthesis にサンプルコードがある。下記はサンプルの一つ。

<script type="text/javascript">
  speechSynthesis.speak(new SpeechSynthesisUtterance('Hello World'));
</script>

フォームに入力した英語の発音をチェックするアプリ

W3Cのサンプルを見ながら、簡単なアプリを作成してみました。
フォームに英単語を入力後、ボタンをクリックすると、英単語の発音が確認できます。


<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>Web Speech API サンプル 2</title>
</head>
<body>
  <h1>英語の音声確認アプリ</h1>

  <div>
    <p>音声を確認したい単語を入力してください。</p>
    <input type="text" id="word"></form>
    <button id="button" onclick="pronounce()">発音を確認</button>
  </div>

<script type="text/javascript">

  'use strict'

  function pronounce() {

    let word = document.getElementById('word').value;
    let u = new SpeechSynthesisUtterance();
    u.lang = 'en-US';
    u.text = word;
    speechSynthesis.speak(u);

  }

</script>

</body>
</html>

実際に動くサンプルは下記です。

26
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
23