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
相关推荐
执子念的飞鱼15 分钟前
浏览器直接预览 Pages、Numbers、Keynote:iWork 格式真正难在哪
前端·javascript
alloc18 分钟前
从延迟聚合到可解释诊断:MetricKit 的原理与工程化实践
前端
颜进强19 分钟前
06 - OpenSpec change 从模糊想法到完整契约:new change / explore / propose 三连
前端·后端·ai编程
Cache技术分享19 分钟前
499. Java 反射 - 获取类型上的注解
前端·后端
用户9210802628619 分钟前
左侧历史对话模块:使用 Conversations 搭建会话入口
前端
用户693717500138420 分钟前
9531 款 AI 工具流量真相:当 90% 的访问涌向 100 个平台,普通创业者还有机会吗?
前端·后端
莫问ABC25 分钟前
HTML、CSS、JavaScript 前端三件套
前端·css·html
颜进强26 分钟前
07 - OpenSpec change 修正带与照单施工:update 修订 + apply 实现
前端·后端·ai编程
京东云开发者37 分钟前
【全栈实践】第一个 AI Agent 项目:从零搭建 AI 音频创作助手【最终版】
前端·vue.js·音视频开发
12.=0.1 小时前
【REVIEW_C】【持续更新】
服务器·前端·javascript