JavaScript文字转语音_SpeechSynthesisUtterance语音合成的使用
web前端开发
共 3366字,需浏览 7分钟
·
2021-12-14 17:49
实例对象属性
lang 获取并设置话语的语言
pitch 获取并设置话语的音调(值越大越尖锐,越低越低沉)
rate 获取并设置说话的速度(值越大语速越快,越小语速越慢)
text 获取并设置说话时的文本
voice 获取并设置说话的声音
volume 获取并设置说话的音量
SpeechSynthesis方法
speak() 将对应的实例添加到语音队列中
cancel() 删除队列中所有的语音.如果正在播放,则直接停止
pause() 暂停语音
resume() 恢复暂停的语音
getVoices 获取支持的语言数组. 注意:必须添加在voiceschanged事件中才能生效
实例对象方法
onpause – 语音合成暂停时候的回调。
onresume – 语音合成重新开始时候的回调。
onend – 语音合成结束时候的回调。
简单实现
let utterThis = new SpeechSynthesisUtterance('你好,世界!');
speechSynthesis.speak(utterThis);
let utterThis = new SpeechSynthesisUtterance();
utterThis.text = '你好,世界!';
utterThis.lang = 'zh';//汉语
utterThis.rate = 0.7;//语速
speechSynthesis.speak(utterThis);
项目实战
<div class="voiceinator">
<h1>听说 5000h1>
<select name="voice" id="voices">
<option value="">Select A Voiceoption>
select>
<label for="rate">Rate:label>
<input name="rate" type="range" min="0" max="3" value="1" step="0.1">
<label for="pitch">Pitch:label>
<input name="pitch" type="range" min="0" max="2" step="0.1">
<textarea name="text">你好 给你点?textarea>
<button id="stop">Stop!button>
<button id="speak">Speakbutton>
div>
const synth = window.speechSynthesis
const msg = new SpeechSynthesisUtterance()
let voices = []
const voicesDropdown = document.querySelector('[name="voice"]')
const options = document.querySelectorAll('[type="range"], [name="text"]')
const speakButton = document.querySelector('#speak')
const stopButton = document.querySelector('#stop')
msg.text = '你好 给你点?'
msg.lang = 'zh-CN'
synth.addEventListener('voiceschanged',getSupportVoices)
speakButton.addEventListener('click',throttle(handleSpeak,1000))
stopButton.addEventListener('click',handleStop)
options.forEach(e => e.addEventListener('change',handleChange))
function getSupportVoices() {
voices = synth.getVoices()
voices.forEach(e => {
const option = document.createElement('option')
option.value = e.lang
option.text = e.name
voicesDropdown.appendChild(option)
})
}
function handleSpeak(e) {
msg.lang = voicesDropdown.selectedOptions[0].value
synth.speak(msg)
}
function handleStop(e) {
synth.cancel(msg)
}
function handleChange(e) {
msg[this.name] = this.value
}
function throttle(fn,delay) {
let last = 0
return function() {
const now = new Date()
if(now - last > delay) {
fn.apply(this,arguments)
last = now
}
}
}
代码解读
遇到问题
window.speechSynthesis.cancel()
if(!!window.SpeechSynthesisUtterance){
console.log("请使用其他浏览器!")
}
评论