vue项目实现文字转换成语音播放功能

一、Web Speech API

Web Speech API 使您能够将语音数据合并到 Web 应用程序中。

Web Speech API 有两个部分:SpeechSynthesis 语音合成 (文本到语音 TTS)和 SpeechRecognition  语音识别(异步语音识别)。我们今天主要了解语音合成,将文字转换成语音播放

二、语音合成

SpeechSynthesis语音合成服务的控制器接口,可用于获取设备上可用的合成语音,开始、暂停以及其它相关命令的信息。

SpeechSynthesisUtterance表示一次发音请求。其中包含了将由语音服务朗读的内容,以及如何朗读它(例如:语种、音高、音量)。

三、SpeechSynthesis方法介绍

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

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

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

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

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

四、SpeechSynthesisUtterance属性介绍

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

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

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

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

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

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

五、vue项目案例

<template>
    <button @click="playVoice">播放语音</button>
</template>
<script>
const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();
export default {
  data() {
    return {};
  },
  methods: {
    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);
    }
  }
};
</script>

文章每周持续更新,可以微信搜索「 前端大集锦 」第一时间阅读,回复【视频】【书籍】领取200G视频资料和30本PDF书籍资料

 

猜你喜欢

转载自blog.csdn.net/qq_38128179/article/details/108343115