SpeechSynthesisUtterance文字语音播报, 循环播报, 方法封装多组件使用, 自定义播报音色音量音调

在这里插入图片描述

老规矩, 先赞后看

1, 基础使用

开始播放, 播放完自动结束

window.speechSynthesis.speak(new SpeechSynthesisUtterance('哈哈哈'))

手动结束

window.speechSynthesis.cancel()

其他参数

let ut = new SpeechSynthesisUtterance('哈哈哈')
    ut.xxx
`text`     – 播放的内容, 例如上面的'哈哈哈'
`lang`     – 播放的语言,例如:`zh-cn`
`voiceURI` – 指定希望使用的声音和服务,字符串。
`volume`   – 音量,区间范围是`0``1`,默认是`1``rate`     – 语速,默认值是`1`,范围是`0.1``10`,表示语速的倍数,例如`2`表示正常语速的两倍。
`pitch`    – 音调,范围从`0`(最小)到`2`(最大)。默认值为`1`。

暴露的方法
`onstart`  – 语音合成开始时候的回调。
`onpause`  – 语音合成暂停时候的回调。
`onresume` – 语音合成重新开始时候的回调。
`onend`    – 语音合成结束时候的回调。

其他方法

window.speechSynthesis.xxxx
speak()   播放
cancel()  结束
pause()   暂停
resume()  恢复暂停的语音

2, 自定义播放次数

function playVoice(text, times = 1) {
      let count = 0
      const play = () => {
        if (count < times) {
          let utterance = new SpeechSynthesisUtterance(text)
          utterance.onend = () => {
            count++
            if (count < times) {
              setTimeout(() => {
                play()
              }, 1000)
            }
          }
          window.speechSynthesis.speak(utterance)
        }
      }
      play()
    }
playVoice('好好好', 3)

3, 多次播放 方法封装使用

新建speech.js

// 定义一个class
class SpeechManager {
  constructor() {
    this.utterance = null
    this.isPlaying = false
    this.repeatTimeout = null
  }

  // 播放语音
  speak(text, options = {}) {
    const {
      repeat = false, // 是否重复播放
      repeatDelay = 500 // 重复播放延迟时间(ms)
    } = options

    // 取消之前的语音
    this.cancel()

    this.utterance = new SpeechSynthesisUtterance(text)

    if (repeat) {
      this.utterance.onend = () => {
        this.repeatTimeout = setTimeout(() => {
          if (this.isPlaying) {
            window.speechSynthesis.speak(this.utterance)
          }
        }, repeatDelay)
      }
    }

    this.isPlaying = true
    window.speechSynthesis.speak(this.utterance)
  }

  // 取消语音播放
  cancel() {
    this.isPlaying = false
    if (this.repeatTimeout) {
      clearTimeout(this.repeatTimeout)
      this.repeatTimeout = null
    }
    window.speechSynthesis.cancel()
  }
}

// 导出
export default new SpeechManager()

在需要使用的页面里导入

import speechManager from '@/util/speech.js'

//某个方法里面需要使用
xxx(){
  // 两个字段, 播放的文本和是否重复播放
  speechManager.speak('请将身份证放置刷卡区或手动输入证件号', { repeat: true })
}


//某个方法里面结束播放
xxx(){
  speechManager.cancel()
}

4, 封装的源码js已经上传, 需要自取 点击前往

没了, 记录一下, 下期再见!
END-------------------

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨同学*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值