vue 实现语音播报

近日又遇到一个需求,需要语音播报,举例:扫码枪扫描条形码,滴~入库成功
一通百度,发现大部分用的还是百度接口,大致看了下,好像还收费,可恶啊
我这里使用的是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

大家根据自己的需求封装,然后导出,挂载全局就行了

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值