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
相关推荐
小灰灰搞电子3 分钟前
Rust+Slint 实现动态流光边框源码分享
开发语言·前端·rust·流光边框
niucloud-admin8 分钟前
NIUCLOUD PHP SAAS上门家政使用文档:机构报表
前端·人工智能
枣把儿28 分钟前
开源!全套公众号写作、封面、发布自动化工具包!
前端·命令行
陶醉的松鼠32 分钟前
前端容易忽略的 debugger 调试技巧
前端
我命由我1234532 分钟前
6-3.Python 异常处理 - 异常处理进阶(else 块与 finally 块、异常传递、自定义异常)
开发语言·前端·数据库·后端·python·学习·java-ee
龙九山36 分钟前
我的 10 个 npm 插件,差点被 AI 判了死刑
前端·开源
deli00739 分钟前
键盘按键测试:按下就点亮,keydown 延迟精确到 1 毫秒
前端
Amos_Web1 小时前
通过 Rspack 源码学 Rust(三):用 Default 与 std::mem::take 取出字段所有权
前端
MetWeave1 小时前
风怎么流动:色斑告诉你多大,告诉不了你去哪
前端·数据可视化
Amos_Web1 小时前
Rspack 源码解析(三十三):Module Federation 如何用 RemoteModule 与 ContainerEntryModule 表示远程代
前端