Skip to content

文字转语音

Web Speech API

h5 新提供的一个原生语音识别技术的 API,可以将文本转成语音并播放。缺点是兼容性不好。

js
/**
 * @description 文字转语音
 * @param {string} message 文字内容
 * @returns {SpeechSynthesis} synth 语音合成接口
 * @returns {SpeechSynthesisUtterance} speechUtterance 要转换为语音的文本内容
 */
export default function speak(message: string) {
  if (!window.SpeechSynthesisUtterance) {
    console.error("当前浏览器不支持文字转语音服务!");
    return;
  }
  if (!message) return;

  // 创建语音合成接口
  const synth: SpeechSynthesis = window.speechSynthesis;
  const speechUtterance: SpeechSynthesisUtterance = new SpeechSynthesisUtterance();
  const voices = synth.getVoices();
  speechUtterance.text = message;
  speechUtterance.rate = 1;
  speechUtterance.lang = "zh-CN";
  speechUtterance.volume = 1;
  speechUtterance.pitch = 1;
  speechUtterance.voices = voices[0];

  synth.speak(speechUtterance);
  return { synth, speechUtterance };
}

speechUtterance 的参数:

参数作用
lang设置语音的语言(zh-CN、en-CS)
pitch设置语音的音调,默认值 1,取值范围 [0, 2],值越大越尖锐
rate设置语音的速度,默认值 1,取值范围 [0, 10],值越大语速越快
text设置语音的文本内容
voice设置语音的音色
volume设置语音的音量,默认值 1,取值为 [0, 1]
onend播放结束的回调函数
onstart播放开始的回调函数
onerror播放出现错误的回调函数
onmark当读到标记文本时的回调
onpause播放暂停
onresume播放重启

synth 的参数:

参数作用
pause()暂停播放
resume()继续播放
cancel()取消播放

Released under the MIT License.