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

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

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

今回は 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> 
 
実際に動くサンプルは下記です。

https://nick-smallworld.github.io/WebSpeechAPIPractice/sample-2.html

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)