Skip to content

使用SpeechSynthesisUtterance实现语音播放功能

项目需求:将文字转换成语音进行播放

文档地址:https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance

SpeechSynthesisUtterance是借助浏览器来实现的语音播放

核心代码:

js
    // 语音播放
    // forNum循环次数
    function voicePlay(forNum) {
      if (!('speechSynthesis'in window)) {
        console.log('当前浏览器不支持SpeechSynthesisUtterance!')
        return
      }
      window.speechSynthesis.cancel()
      const utterThis  = new SpeechSynthesisUtterance()
      utterThis.text = voicePlayText.value
      // volume音量 0-1 1
      // tone音调 0-2 1
      // speed语速 0.1-10

      // 火狐浏览器播放的是英文,所以需要加这个
      utterThis.lang = 'zh-cn'
      utterThis.volume = volume.value/10
      utterThis.pitch = tone.value
      utterThis.rate = speed.value
      // 循环播放
      for (let i = 0; i < forNum; i++) {
        window.speechSynthesis.speak(utterThis)
      }
    }

备注

谷歌浏览器需要用click方法触发,可以用js模拟个click方法

这个方法在最新的谷歌浏览器里不能用,解决办法是使用Edge浏览器打开

html
  <el-button ref="buttonRef" @click="voicePlay" style="display: none"></el-button>
js
if (navigator.userAgent.indexOf('Chrome') > -1) {
      buttonRef.value.$el.click(voicePlayText)
    } else {
      voicePlay(voicePlayText)
    }

如有转载或 CV 的请标注本站原文地址