SpeechSynthesisUtterance 介绍
- HTML5中新增的API
SpeechSynthesisUtterance
, 可以将文字合成为对应的语言。
SpeechSynthesisUtterance 属性
SpeechSynthesisUtterance.lang
获取并设置话语的语言SpeechSynthesisUtterance.pitch
获取并设置话语的音调(值越大越尖锐,越低越低沉)SpeechSynthesisUtterance.rate
获取并设置说话的速度(值越大语速越快,越小语速越慢)SpeechSynthesisUtterance.text
获取并设置说话时的文本SpeechSynthesisUtterance.voice
获取并设置说话的声音SpeechSynthesisUtterance.volume
获取并设置说话的音量
SpeechSynthesisUtterance.text 基本方法
speak()
将对应的实例添加到语音队列中cancel()
清空队列中的所有声音,并停止播放pause()
暂停resume()
恢复暂停的语音getVoices()
获取支持的语言数组 注意: 这里必须在voiceschanged 事件中
speechSynthesis.addEventListener('voiceschanged', () => {
speechSynthesis.getVoices()
})
笔记转载 https://blog.csdn.net/qq_40571631/article/details/89738575
项目案例
HTML
<label for="voices">语言:</label>
<select name="voice" id="voices">
<option value="">请选择</option>
</select>
<label for="rate">语速:</label>
<input name="rate" type="range" min="0" max="3" value="1" step="0.1">
<label for="pitch">音调:</label>
<input name="pitch" type="range" min="0" max="2" step="0.1">
<textarea name="text"></textarea>
<button onclick="startAudio()">点击播放语音</button>
<button onclick="stopAudio()">点击暂停语音</button>
Js 部分
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 // 设置语言
// utterance.voice = voices[20] // 13 日语
speechSynthesis.speak(utterance)
}
// 点击暂停语音
function stopAudio () {
speechSynthesis.cancel(utterance)
}