近日又遇到一个需求,需要语音播报,举例:扫码枪扫描条形码,滴~入库成功
一通百度,发现大部分用的还是百度接口,大致看了下,好像还收费,可恶啊
我这里使用的是speak-tts,传送门
npm install speak-tts
封装为全局方法
import Speech from 'speak-tts'
const speech = new Speech() // will throw an exception if not browser supported
if (speech.hasBrowserSupport()) {
// returns a boolean
console.log('speech synthesis supported')
} else {
alert('The browser does not support voice')
}
初始化
speech
.init({
volume: 1,
lang: 'zh-CN',
rate: 1,
pitch: 1,
voice: null,
splitSentences: true
})
.then((data) => {
// The "data" object contains the list of available voices and the voice synthesis params
console.log('Speech is ready, voices are available', data)
})
.catch((e) => {
console.error('An error occured while initializing : ', e)
})
详细参数请查阅文档
!!!踩坑来了,voice这个为设置方言(就是发音),我本来使用的是demo的’voice’:‘Google UK English Male’,然后声带就落家了,根据我的猜测是因为这个发音浏览器不支持,所以我设置了null,让他根据浏览器来,浪费了一波时间,可恶啊。
调用
const speak = (text) => {
speech
.speak({
text: newText,
queue: false, // current speech will be interrupted,
listeners: {
onstart: () => {
console.log('Start utterance')
},
onend: () => {
console.log('End utterance')
},
onresume: () => {
console.log('Resume utterance')
},
onboundary: (event) => {
console.log(event.name + ' boundary reached after ' + event.elapsedTime + ' milliseconds.')
}
}
})
.then(() => {
console.log('Success !')
})
.catch((e) => {
console.error('An error occurred :', e)
})
}
export default speak
大家根据自己的需求封装,然后导出,挂载全局就行了