1
3

More than 3 years have passed since last update.

【Javascript】Javascriptで読み上げ【そのままコピペOK】

Last updated at Posted at 2020-12-06

結論

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  </head>
  <body>
        <div>
            <input id="text" type="text" max="255" value="こんにちわ" />
            <a onclick="speak()">CLICK ME</a>
        </div>
        <script>
            //text読み上げ
            let isSpeech = false;
            if ('speechSynthesis' in window) {
                isSpeech = true;
            } else {
                alert("このブラウザは音声合成に対応していません。")
            }
            function speak(){
                if (isSpeech){
                    var speak   = new SpeechSynthesisUtterance();
                    speak.text  = document.getElementById('text').value;
                    speak.rate  = 1; // 読み上げ速度 0.1-10 初期値:1 (倍速なら2, 半分の倍速なら0.5, )
                    speak.pitch = 1; // 声の高さ 0-2 初期値:1
                    speak.lang  = 'ja-JP'; //(日本語:ja-JP, アメリカ英語:en-US, イギリス英語:en-GB, 中国語:zh-CN, 韓国語:ko-KR)
                    var voice = speechSynthesis.getVoices().find(function(voice){
                        return voice.name === 'Google 日本語';
                    });
                    // 取得できた場合のみ適用する
                    if(voice){
                        speak.voice = voice;
                    }
                    speechSynthesis.speak(speak);
                }
            }
        </script>
  </body>
</html>
1
3
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
1
3