制作ブログ Web制作マークアップJavaScript文字列を読み上げる → Web Speech API / Speech Synthesis API

文字列を読み上げる → Web Speech API / Speech Synthesis API

まずはこれ。

// 読み上げます
var speech = new SpeechSynthesisUtterance();

基本セット

// 読み上げるテキストをセットする
speech.text = "It always seems impossible until it's done.";
// 言語をセットする
speech.lang = "en-US";
// 速度を調整する(0.1〜10)*言語によってレンジは異なる
speech.rate = 1.0;
// ピッチを調整する(0.0 〜 2.0)*言語によってレンジは異なる
speech.pitch = 1.0;

音声のコントロール

// 再生する
speechSynthesis.speak(speech);
// 一時停止する
speechSynthesis.pause(speech);
// 一時停止解除(再開)する
speechSynthesis.resume(speech);
//  キャンセル(停止) する
speechSynthesis.speak(speech);

speech.lang 補足

  • ja-JP 日本語
  • en-US アメリカ英語
  • en-GB イギリス英語
  • it-IT イタリア語
  • fr-FR フランス語
  • de-DE ドイツ語
  • es-ES スペイン語
  • ko-KR 韓国語
  • zh-CN 中国語

speechSynthesis.getVoices() で取得した配列の中に、lang以外にも、voiceURI を取得できて、それをセットすることもできる(セットするサンプル: speech.voiceURI = “Kyoko”;)。

いろんな音声をセットする

Chrome 58.x(2017年6月現在の最新バージョン)では、実に66種類(!)の音声が用意されている。

// 音声リストを取得する
speechSynthesis.speak("");
setTimeout(function(){
voices = speechSynthesis.getVoices();
}, 100);

speack後でないと音声の種類は取得できないので注意、さらにspeack直後も取得できないのでさらに注意。

speech.voice = voices[0];

ブラウザによって種類は異なるので注意。

音声が再生できるブラウザか判別する

if (window.speechSynthesis) {
}

ブラウザ対応状況を、Can I use で確認。Can I use / Speech Synthesis API

ちなみに、Speech Synthesis API ではなく、Speech Recognition API もありましたが、こちらをサポートするブラウザはありません。Can I use / Speech Recognition API