使用Web Speech进行文字转语音并播放

120 阅读1分钟
<!DOCTYPE html>
<html lang="zh-cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>文字转语音播报</title>
</head>
<body>
    <div>
        <input type="text" id="words">
        <button onclick="play()">播报</button>
        <button onclick="pause()">暂停</button>
        <button onclick="resume()">继续</button>
        <button onclick="stop()">停止</button>
    </div>
</body>
<script>
    const synth = window.speechSynthesis;
    const msg = new window.SpeechSynthesisUtterance();
    const play=()=>{
        const text=document.getElementById('words').value;
        if(text){
            msg.text = text;
            msg.lang = "zh-CN"; //语言
            msg.volume = 1; //音量:0~1,默认1
            msg.rate = 1; //语速:0.1~10,默认1
            msg.pitch = 1; //音高:0~2,默认1
            synth.speak(msg);
        }

    }
    const pause=()=>{
        synth.pause(msg);
    }
    const resume=()=>{
        synth.resume(msg);
    }
    const stop=()=>{
        synth.cancel(msg);
    }

</script>

</html>