SpeechSynthesisUtterance基本介绍
SpeechSynthesisUtterance.lang
是HTML5中新增的API,用于将指定文字合成为对应的语音.也包含一些配置项,指定如何去阅读(语言,音量,音调)等
官方文档地址(https://developer.mozilla.org/zh-CN/docs/Web/API/SpeechSynthesisUtterance)
SpeechSynthesisUtterance基本属性
SpeechSynthesisUtterance.lang
获取并设置话语的语言
SpeechSynthesisUtterance.pitch
获取并设置话语的音调(值越大越尖锐,越低越低沉)
SpeechSynthesisUtterance.rate
获取并设置说话的速度(值越大语速越快,越小语速越慢)
SpeechSynthesisUtterance.text
获取并设置说话时的文本
SpeechSynthesisUtterance.voice
获取并设置说话的声音
SpeechSynthesisUtterance.volume
获取并设置说话的音量
SpeechSynthesisUtterance.text
基本方法
speak()
将对应的实例添加到语音队列中
cancel()
删除队列中所有的语音.如果正在播放,则直接停止
pause()
暂停语音
resume()
恢复暂停的语音
getVoices
获取支持的语言数组. 注意:必须添加在voiceschanged事件中才能生效
使用demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <label for="voices">语言:</label> <select name="voice" id="voices"> <option value="">请选择</option> <!-- <option value="Google_SC">Google 普通话(中国大陆)</option> <option value="Kangkang_SC">Microsoft Kangkang - Chinese (Simplified, PRC)</option> --> </select> </div> <div> <label for="rate">语速:</label> <input id="rate" name="rate" type="range" min="0" max="3" value="1" step="0.1"> </div> <div> <label for="pitch">音调:</label> <input id="pitch" name="pitch" type="range" min="0" max="2" step="0.1"> </div> <div> <textarea id="text" name="text"></textarea> </div> <div> <button onclick="startAudio()">点击播放语音</button> </div> <div> <button onclick="stopAudio()">点击结束语音</button> </div> <div> <button onclick="pauseAudio()">点击暂停语音</button> </div> <div> <button onclick="resumeAudio()">恢复暂停的语音</button> </div> </body> <script> let utterance = new SpeechSynthesisUtterance() // 创建 语音对象 // 获取元素对象 let dom_voices = document.querySelector('#voices') const options = document.querySelectorAll('[type="range"], [name="text"]') options.forEach(e => e.addEventListener('change', handleChange)) // voiceschanged 事件 speechSynthesis.addEventListener('voiceschanged', () => { let voices = speechSynthesis.getVoices(); // 根据系统语音创建选项 voices.forEach(e => { const option = document.createElement('option') option.value = e.lang option.text = e.name dom_voices.appendChild(option) }) }) // 发生改变时触发 function handleChange(e) { // console.log(this.name, this.value); utterance[this.name] = this.value } function startAudio() { utterance.lang = dom_voices.selectedOptions[0].value // 设置语言 speechSynthesis.speak(utterance); } // 点击结束语音 function stopAudio() { speechSynthesis.cancel(utterance) } function pauseAudio() { speechSynthesis.pause(utterance) } function resumeAudio() { speechSynthesis.resume(utterance); } </script> </html>