只适用于有window对象的环境。
代码示例
<template>
<button @click="playVoice">播放语音</button>
</template>
<script>
const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
export default {
data() {
return {};
},
methods: {
playVoice() {
this.handleSpeak('小朋友,你是否有很多问号') // 传入需要播放的文字
},
// 语音播报的函数
handleSpeak(text) {
msg.text = text; // 文字内容: 小朋友,你是否有很多问号
msg.lang = "zh-CN"; // 使用的语言:中文
msg.volume = 1; // 声音音量:1
msg.rate = 1; // 语速:1
msg.pitch = 1; // 音高:1
synth.speak(msg); // 播放
},
// 语音停止
handleStop(e) {
msg.text = e;
msg.lang = "zh-CN";
synth.cancel(msg);
}
}
};
</script>
SpeechSynthesisUtterance是HTML5中新增的API,用于将指定文字合成为对应的语音.也包含一些配置项,指定如何去阅读(语言,音量,音调)等。
SpeechSynthesisUtterance基本属性
- SpeechSynthesisUtterance.lang 获取并设置话语的语言
- SpeechSynthesisUtterance.pitch 获取并设置话语的音调(值越大越尖锐,越低越低沉)
- SpeechSynthesisUtterance.rate 获取并设置说话的速度(值越大语速越快,越小语速越慢)
- SpeechSynthesisUtterance.text 获取并设置说话时的文本
- SpeechSynthesisUtterance.voice 获取并设置说话的声音
- SpeechSynthesisUtterance.volume 获取并设置说话的音量
SpeechSynthesisUtterance.text基本方法 - speak() 将对应的实例添加到语音队列中
- cancel() 删除队列中所有的语音.如果正在播放,则直接停止
- pause() 暂停语音
- resume() 恢复暂停的语音
- getVoices 获取支持的语言数组. 注意:必须添加在voiceschanged事件中才能生效