Vue语音播报,不用安装任何包和插件,直接调用。

Vue语音播报功能可以通过使用浏览器提供的Web Speech API来实现。这个API允许你的应用程序通过浏览器朗读文本,不用安装任何包和插件,直接调用。以下是一个简单的介绍,演示如何在Vue中使用语音提示功能:

一、JS版本

TypeScript 复制代码
<template>
  <el-button type="success" @click="playVoice">Web Speech API</el-button>
</template>
<script>
const synth = window.speechSynthesis // 启用文本
const msg = new SpeechSynthesisUtterance()
export default {
  data() {
    return {
    }
  },
  methods: {
    playVoice() {
      this.handleSpeak('测试111111111') // 传入需要播放的文字
    },
    // 语音播报的函数
    handleSpeak(text) {
      msg.text = text // 内容
      msg.lang = 'zh-CN' // 使用的语言:中文
      msg.volume = 1 // 声音音量:1
      msg.rate = 1 // 语速:1
      msg.pitch = 1 // 音高:1
      synth.speak(msg) // 播放
    },
    // 语音停止
    handleStop(e) {
      msg.text = e
      msg.lang = 'zh-CN'
      synth.cancel(msg) // 取消该次语音播放
    }
  }
}
</script>

二、TS版本

运用TS封装形式来实现语音播报功能。

创建一个VoiceAnnouncements.ts的文件,然后在应用的Vue页面进行引入该ts文件并使用。

TypeScript 复制代码
class VoiceAnnouncements {
    public synth = window.speechSynthesis // 启用文本
    public msg: any = new SpeechSynthesisUtterance()
    public language: string = 'zh-CN'  // 使用的语言:中文
    public volume: number = 1 // 音量
    public speed: number = 1  // 语速
    public pitch: number = 1 // 音高

    // 开始语音提示
    startVoiceFunction = (content: String) => {
        this.msg.text = content
        this.msg.language = this.language 
        this.msg.volume = this.volume 
        this.msg.speed = this.speed
        this.msg.pitch = this.pitch
        this.synth.speak(this.msg) 
    }
    // 停止语音提示
    stopVoiceFunction = (content: any) => {
        this.msg.text = content
        this.msg. language = this. language
        this.synth.cancel(this.msg) 
    }

}

//传出实例,保证整个系统只存在单例的Voice
const VoiceAnnouncementsInstance = new VoiceAnnouncements()

export default VoiceAnnouncementsInstance
相关推荐
ZhengEnCi6 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
kyriewen7 小时前
我给 61 个前端库排了两次名,最多差了 46 位
前端·javascript·程序员
程序员大阳7 小时前
副队长Vue3教程(33)--路由懒加载
vue.js·性能优化·vue3·路由·懒加载·速度慢
亲亲小宝宝鸭7 小时前
Cesium启动:TLE数据是如何变成轨迹线的
前端·cesium
阿里云云原生7 小时前
对话即构建,在 AgentCore 构建 Agent 就是这么简单
前端·agent
夕水8 小时前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript
狗头大军之江苏分军9 小时前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬9 小时前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
parade岁月10 小时前
VTable Guild 3.0.0 发布,面向 Vue 3 的 ProTable 式业务表格
前端
xurileidian10 小时前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python