js vue 文本转换语音

介绍:

我们可以调用window中内置api,实现语音转换,简单介绍下需要用到的两个api

SpeechSynthesis

.cancel() 移除所有语音谈话队列中的谈话。

.getVoices() 返回当前设备所有可用声音的 SpeechSynthesisVoice列表。

.pause() 把 SpeechSynthesis 对象置为暂停状态。

.resume() 把 SpeechSynthesis 对象置为一个非暂停状态:如果已经暂停了则继续。

.speak() 添加一个utterance到语音谈话队列;它将会在其他语音谈话播放完之后播放。

 SpeechSynthesisUtterance

.lang 设置话语的语言。 例如:“zh-cn”表示中文

.pitch 设置说话的音调(音高)。范围从0(最小)到2(最大)。默认值为1

.rate 设置说话的速度。默认值是1,范围是0.1到10,表示语速的倍数,例如2表示正常语速的两倍

.text 设置在说话时将合成的文本内容。

.voice 设置用于说话的声音。

.volume 设置将在其中发言的音量。区间范围是0到1,默认是1

示例

const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
playVoice () {
  this.handleSpeak('你好呀,很高兴认识你') // 传入需要播放的文字
},
// 语音播报的函数
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);
}

在vue中使用 speak-tts 插件

安装

npm install speak-tts

main.js引入

import Speech from 'speak-tts' // es6
// var Speech = require('speak-tts') //if you use es5
const speech = new Speech()
Vue.prototype.$speech = speech

使用

<button @click="plugVoice">点击</button>
<button @click="$speech.pause()">暂停</button>
<button @click="$speech.resume()">继续</button>
<button @click="$speech.cancel()">取消</button>
plugVoice () {
  // 判断浏览器是否支持
  if (!this.$speech.hasBrowserSupport()) return alert('该浏览器不支持语音播放')
    // this.$speech.init() 用于设置语言、音量、语速、音高等。如果不设置将使用浏览器默认的语言
    this.$speech.speak({ text: '你好呀,很高兴认识你' })
},

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Write λ Code

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

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

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

打赏作者

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

抵扣说明:

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

余额充值