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
相关推荐
万少44 分钟前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站3 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名5 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫6 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊6 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter6 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折6 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_6 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码16 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial6 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js