4
6

More than 3 years have passed since last update.

javascriptでテキスト音声読み上げ

Last updated at Posted at 2020-01-25

はじめに

javascriptでお手軽に音声読み上げできます。
Web Speech Synthesis API を使います。無料なのがうれしい(^^)

20200125_speechAPE_speak.jpg

自分用メモまで。お勉強中です

環境 

windows10
python3 (anaconda) 
(※動作確認まで ローカルホスト起動できれば、pythonでなくruby, apacheなどでもよいみたいです)

ブラウザ MicrosoftEdge (ver44?)
ブラウザ Chrome(ver74?)

ソースコード

下記HTMLを作成して、
C:\Users\自分のユーザーのフォルダ\sample.html として保存します。

sample.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>音声読み上げ</title>
</head>
<body>
<h1>音声合成</h1>
<input class="text" value="Speech API を使おう。" style="width: 80%; height: 40px; font-size: 40px;" />
<button onclick="speak()" style="height: 30px; width: 80px;">speak</button>

<!-- スクリプト部分 -->
<script>
function speak(){
  var speak   = new SpeechSynthesisUtterance();
  speak.text  = document.querySelector('.text').value;
  speak.rate  = 1; // 読み上げ速度 0.1-10 初期値:1 (倍速なら2, 半分の倍速なら0.5, )
  speak.pitch = 0; // 声の高さ 0-2 初期値:1(0で女性の声) 
  speak.lang  = 'ja-JP'; //(日本語:ja-JP, アメリカ英語:en-US, イギリス英語:en-GB, 中国語:zh-CN, 韓国語:ko-KR)

  sleep(2000);
  speechSynthesis.speak(speak);

}

function sleep(time){
  var date_1 = new Date().getTime();
  var date_2 = new Date().getTime();
  while (date_2 < date_1 + time){
    date_2 = new Date().getTime();
  }
  return;
};
</script>

<body>
<html>

#動作確認
ローカルWEBサーバー起動
※ webサーバー経由必須です。単体 sample.html だけでは機能しません。

python -m http.server 8080

ブラウザでアクセスします。
http://localhost:8080/sample.html

ボタンをクリックするとテキストボックスの中身を読み上げます。

これからしたいこと

・声の種類をいろいろ変更できるようにしたい
など

参考

参考 ソースコード: 【javascriptで実装!】Web Speech Synthesis APIを使ってブラウザで音声読み上げをしよう
https://shinmedia20.com/javascript-speech-synthesis

参考 APIの使い方: Webページでブラウザの音声合成機能を使おう - Web Speech API Speech Synthesis
https://qiita.com/hmmrjn/items/be29c62ba4e4a02d305c

4
6
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
4
6