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: '你好呀,很高兴认识你' })
},

猜你喜欢

转载自blog.csdn.net/Story_0809/article/details/128529936