SpeechSynthesisUtterance 语音合成使用
SpeechSynthesisUtterance基本属性方法
- SpeechSynthesisUtterance.lang 获取并设置话语的语言
- SpeechSynthesisUtterance.pitch 获取并设置话语的音调(值越大越尖锐,越低越低沉)
- SpeechSynthesisUtterance.rate 获取并设置说话的速度(值越大语速越快,越小语速越慢)
- SpeechSynthesisUtterance.text 获取并设置说话时的文本
- SpeechSynthesisUtterance.voice 获取并设置说话的声音
- SpeechSynthesisUtterance.volume 获取并设置说话的音量
- SpeechSynthesisUtterance.text基本方法
使用方法
- speak() 将对应的实例添加到语音队列中
- cancel() 删除队列中所有的语音.如果正在播放,则直接停止
- pause() 暂停语音
- resume() 恢复暂停的语音
- getVoices 获取支持的语言数组. 注意:必须添加在voiceschanged事件中才能生效
创建一个类:
class Voices {
constructor(text,isPlay) {
this.synth = window.speechSynthesis;
this.msg = new SpeechSynthesisUtterance(text);
this.msg.text = text; // 文字内容
this.msg.lang = "zh-CN"; // 使用的语言:中文
this.msg.volume = 100; // 声音音量:1
this.msg.rate = 0.75; // 语速:1
this.msg.pitch = 10; // 音高:1
this.isPlay = isPlay;
//获取声音列表并设置声音
this.synth.addEventListener('voiceschanged',()=>{
this.msg.voice = this.synth.getVoices()[0];//语种
console.log(this.msg.voice)
});
}
play(){
setTimeout(() => {
speechSynthesis.speak(this.msg);
}, 500);
}
}
调用该方法:
<script type="text/javascript" charset="utf-8" src="./Voices.js"></script>
<script type="text/javascript" charset="utf-8">
window.onload = ()=>{
let res = new Voices('测试语音',true);
res.play();
}
注意:如果谷歌版本太高,只有触发点击事件才有效哦
已经测试完毕~
本文来自博客园,作者:Carvers,转载请注明原文链接:https://www.cnblogs.com/carver/articles/16890225.html

浙公网安备 33010602011771号