Web Speech API-语音合成

1,639 阅读2分钟

image.png

使用场景

通过 TTS 引擎把文本转化成语音输出,web使用在网页文字转语音播放、页面阅读等功能上

依赖windows的TTS引擎

知识点

Web Speech API 使您能够将语音数据合并到 Web 应用程序中。 Web Speech API 有两个部分:SpeechSynthesis 语音合成(文本到语音 TTS)和 SpeechRecognition 语音识别(异步语音识别)。

API 包含以下两个部分:

-语音识别:通过 SpeechRecognition 接口进行访问,它提供了识别从音频输入(通常是设备默认的语音识别服务)中识别语音情景的能力。一般来说,你将使用该接口的构造函数来构造一个新的 SpeechRecognition 对象,该对象包含了一系列有效的对象处理函数来检测识别设备麦克风中的语音输入。SpeechGrammar 接口则表示了你应用中想要识别的特定文法。文法则通过 JSpeech Grammar Format (JSGF.) 来定义。

-语音合成:通过 SpeechSynthesis 接口进行访问,它提供了文字到语音(TTS)的能力,这使得程序能够读出它们的文字内容(通常使用设备默认的语音合成器)。不同的声音类类型通过 SpeechSynthesisVoice (en-US) 对象进行表示,不同部分的文字则由 SpeechSynthesisUtterance 对象来表示。你可以将它们传递给 SpeechSynthesis.speak() (en-US) 方法来产生语音。

语音合成

  • SpeechSynthesis 用于获取设备上关于可用的合成声音的信息,开始、暂停语音,或除此之外的其他命令
  • SpeechSynthesis.getVoices() 返回当前设备所有可用声音的 SpeechSynthesisVoice列表--异步方法
  • SpeechSynthesis.onvoiceschanged 当由SpeechSynthesis.getVoices()方法返回SpeechSynthesisVoice列表改变时触发。
  • SpeechSynthesis.speak()添加一个utterance 到语音谈话队列;在其他语音谈话播放完之后播放
  • SpeechSynthesisUtterance 一次发音请求,包含将由语音服务朗读的内容,以及如何朗读它(例如:语种、音高、音量),用于speak

SpeechSynthesisUtterance.lang 语种
SpeechSynthesisUtterance.voice 语音包
SpeechSynthesisUtterance.volume 音量

  • SpeechSynthesisVoice 系统提供的一个声音。每个 SpeechSynthesisVoice 都有与之相关的发音服务,包括了语种、名称 和 URI 等信息。也就是getVoices()返回的数据对象

SpeechSynthesisVoice.lang
SpeechSynthesisVoice.voiceURI

代码实现

vue2环境下

<el-button @click='speekNotice'>播放</el-button>

data(){
  return {
     speech: {
        allVoices: [],
        synth: window.speechSynthesis
      }
  }
},
created () {
    //注册获取语音包事件
    this.speech.synth.addEventListener('voiceschanged', () => {
      this.speech.allVoices = this.speech.synth.getVoices();
      console.log('this.speech==', this.speech)
    })
}
speekNotice () {
  if (typeof SpeechSynthesisUtterance !== undefined) {
    if (this.speech.allVoices.length > 0) {
      let voiceUtt = new SpeechSynthesisUtterance('你好123')
      voiceUtt.voice = this.speech.allVoices.filter(item => item.localService === true && item.lang === 'zh-CN')[0]
      this.speech.synth.speak(voiceUtt)
    } else {
      console.log('this.speech:', this.speech);
    }
  }
},

注意点

  • getVoices是异步事件,需要等到加载完成后才能获取到
  • TTS依赖