JavaScriptでブラウザに音声を読み上げさせる方法|speechSynthesisの使い方とサンプルコード
window.speechSynthesis.speak() を使ってブラウザにテキストを読み上げさせる方法を解説します。
音声一覧は window.speechSynthesis.getVoices() で取得でき、好きな声を選択可能です。
速度や声の高さも調整可能です。
Webページでテキストを読み上げる機能を実装したい場合に便利なAPIです。
以下のサンプルコードを使えば、入力した文字をブラウザが話す機能を簡単に実装できます。
Webページにナレーション機能(記事の読み上げなど)やテキスト読み上げ(音声アシスタント)を追加する際に便利です。
話させたい文字を入力して「話す」ボタンを押すと読み上げます
このデモでは、「話す」ボタンを押すとリアルタイムで入力したテキストを音声で読み上げます。
speechSynthesis API を使い、好きな声を選択することも可能です。
ソースコード
<input type="text" id="speech_text" value="ここに入力した文字列をブラウザがしゃべります。" size="50"><br>
<input type="button" id="speech_button" value="話す">
<script>
var voices = [];
function speech(){
const uttr = new SpeechSynthesisUtterance(document.getElementById("speech_text").value);
// 話す速度 0.0(遅い)~1.0(標準)~2.0(速い)
uttr.rate=1.0;
// ピッチ(声の高さ) 0.0(低め)~1.0(標準)~2.0(高め)
uttr.pitch=1.0;
// お話が完了したときの関数
uttr.onend=function(){
//iOS14.7.1のsafariはイベントが発生しない
//alert("お話終了");
}
//日本語の音声は、以下のような値から選べる。選ばない場合はデフォルト設定
/*
uttr.voice=window.speechSynthesis.getVoices().filter(
//voice => voice.name==='Microsoft Haruka Desktop - Japanese' //FireFox,Chrome
//voice => voice.name==='Microsoft Nanami Online (Natural) - Japanese (Japan)' //Edgeのみ可
//voice => voice.name==='Microsoft Ayumi - Japanese (Japan)' //Edge,Chromeのみ可
//voice => voice.name==='Microsoft Haruka - Japanese (Japan)' //Edge,Chromeのみ可
//voice => voice.name==='Microsoft Ichiro - Japanese (Japan)' //Edge,Chromeのみ可
//voice => voice.name==='Microsoft Sayaka - Japanese (Japan)' //Edge,Chromeのみ可
//voice => voice.name==='Google 日本語' //Chromeのみ可
)[0];
*/
window.speechSynthesis.cancel();
// お話しする
window.speechSynthesis.speak(uttr);
//お話の一時停止
//window.speechSynthesis.pause();
//お話の再開
//window.speechSynthesis.resume();
//お話の終了
//window.speechSynthesis.cancel();
}
window.addEventListener("load",function(){
//ボタンを押すと「speech」関数を呼び出す
document.getElementById("speech_button").addEventListener("click",speech);
//事前に音声一覧を取得する
if(typeof window.speechSynthesis.onvoiceschanged==="undefined" || window.speechSynthesis.onvoiceschanged===null){
window.speechSynthesis.onvoiceschanged = function(){
setTimeout(function(){
voices = window.speechSynthesis.getVoices();
if(voices.length>0){
//音声一覧をコンソールログに出力する場合
for(let i=0;i<voices.length;i++){
console.log(voices[i].name);
}
// 音声一覧が取得できたらボタンを有効化
document.getElementById("speech_button").removeAttribute("disabled");
document.getElementById("speech_button").parentNode.classList.remove("ui-state-disabled");
}
},100);
}
}else{
setTimeout(function(){
voices = window.speechSynthesis.getVoices();
if(voices.length>0){
//音声一覧をコンソールログに出力する場合
for(let i=0;i<voices.length;i++){
console.log(voices[i].name);
}
// 音声一覧が取得できたらボタンを有効化
document.getElementById("speech_button").removeAttribute("disabled");
document.getElementById("speech_button").parentNode.classList.remove("ui-state-disabled");
}
},100);
}
});
</script>
