Web Speech API を使ってブラウザで音声合成を行う

Web Speech APIを使い、ブラウザで音声を読み上げる方法です。
Web Speech API音声合成非同期音声認識の2つの部分から成り立っていますが、今回は音声合成の部分になります。

音声認識と違い、オフラインやhttp通信でも音声合成できます。

初期化

次の処理をページロード時に1度実行します。 Chrome は一度目のコールが空配列となるため、speechSynthesis.getVoices()をコールしておきます。

speechSynthesis.getVoices();

音声の読み上げ

音声合成により読み上げはspeechSynthesis.speak()で行います。
パラメータのutteranceSpeechSynthesisUtteranceオブジェクトでこちらに音声合成する文章や声の種類を設定します。

const utterance = new SpeechSynthesisUtterance("読み上げたい内容");
let voice = speechSynthesis.getVoices()[0];
utterance.voice = voice;
speechSynthesis.speak(utterance);

サンプル

テキストボックスに入力された文字列を男性の声で読み上げるサンプルです。

条件は分かっていませんが、1回目の再生ボタンで音声が読み上げられない場合があります。
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>speak synthesis</title>
    <script>
        // Chrome は1度目のコールが空配列.
        speechSynthesis.getVoices();

        function onPlay() {
            let textBox = document.getElementById('inputText');
            let text = textBox.value;
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.volume = 1;
            utterance.lang = "ja-JP";
            let voice = speechSynthesis.getVoices().find((voice) => {
                console.log(voice.name);
                return voice.name === 'Microsoft Ichiro - Japanese (Japan)';
            });
            if (voice) {
                utterance.voice = voice;
            }
            speechSynthesis.speak(utterance);
        }
    </script>
</head>
<body>
    <div style="margin: 0 0 1em">
        <input type="text" id="inputText" size="50">
    </div>
    <div style="margin: 0 0 1em">
        <button type="button" onclick="onPlay();">再生</button>
    </div>
</body>
</html>
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です