基于es6的语音播报方法
/**
* text – 要合成的文字内容,字符串
* lang – 使用的语言,字符串, 例如:“zh-cn”
* voiceURI – 指定希望使用的声音和服务,字符串
* volume – 声音的音量,区间范围是0到1,默认是1
* rate – 语速,数值,默认值是1,范围是0.1到10,表示语速的倍数,例如2表示正常语速的两倍。
* pitch – 表示说话的音高,数值,范围从0(最小)到2(最大)。默认值为1
* closeSpeakTime – 表示关闭语音播报的事件,值为毫秒数,为0时不关闭。默认值为0
*/
export const speak = ({text = '', pitch = 2, lang = 'zh-CN', rate = 1, volume = 1, closeSpeakTime = 0}) => {
const msg = Object.assign(new SpeechSynthesisUtterance(), {text, lang, volume, rate, pitch});
speechSynthesis.speak(msg);
// 关闭语音
if (closeSpeakTime) {
setTimeout(() => {
speechSynthesis.cancel(msg)
}, closeSpeakTime)
}
}
speechSynthesis是window的变量,可以直接省去window不写,完整的写法是window.speechSynthesis.speak(msg);