JS文字转语音技术实现
前言
公司要做一个AI语音智能播报功能的实现,所以从网上搜索了几种方法。
一、Web Speech API

developer.mozilla.org/zh-CN/docs/...
主要是Web Speech 的一些概念及用法。
mdn中的使用 Web Speech API developer.mozilla.org/zh-CN/docs/...
主要是Web Speech 的使用和案例。
以下是一些回调函数
speech.lang 获取并设置话语的语言(en-US、zh-CN)
speech.pitch 获取并设置话语的音调 (值越大越尖锐,range:0-2, default:1, float)
speech.rate 获取并设置说话的速度 (值越大语速越快, range:0.1-10, default:1, float)
speech.text 获取并设置说话时的文本
speech.voice 获取并设置说话的声音
speech.volume 获取并设置说话的音量 (range: 0-1, default:1, float)
speech.onboundary
speech.onend 播放结束的回调
speech.onerror 播放出现错误的回调
speech.onmark 当读到标记文本时的回调
speech.onpause 播放暂停
speech.onresume 播放重启
speech.onstart 播放开始的回调
js
const synth = window.speechSynthesis;
// 音高
const pitch = 1;
// 语速
const rate = 1.2;
//inputValues是要播放的文本内容
function speak(inputValues: string) {
if (typeof synth === "undefined") {
return;
}
if (!window.SpeechSynthesisUtterance) {
console.warn("当前浏览器不支持文字转语音服务");
return;
}
if (synth.speaking) {
console.error("speechSynthesis.speaking");
return;
}
if (inputValues !== "") {
console.log("开始播放");
const utterThis = new SpeechSynthesisUtterance(inputValues);
utterThis.onerror = function (event: SpeechSynthesisErrorEvent) {
console.error("SpeechSynthesisUtterance.onerror" + event);
synth.cancel();
};
utterThis.voice = synth.getVoices()[0];
utterThis.pitch = pitch;
var ua = navigator.userAgent;
//这里我判断是否是火狐浏览器,因为不同浏览器的语速不太一样
let isFireFox = /(?:Firefox)/.test(ua);
isFireFox ? (utterThis.rate = rate) : (utterThis.rate = 1.5);
// utterThis.rate = rate;
synth.speak(utterThis);
}
}
二、speak-tts
浏览器的语音合成 (tts)。包装浏览器语音合成 API (developer.mozilla.org/en-US/docs/... 并提供类似的接口,它通过以下方式改进它:
- 给出一个基于承诺的API(init()和speak()方法分别返回一个Promise) -> init() 加载语音后得到解析 -> speak() 在全文说完后得到解决
- 处理Chrome以异步方式加载语音而其他浏览器不加载语音的事实 -> onvoices更改的侦听器在所有浏览器中被触发
- 处理IOS / Android设备和某些Chrome / Firefox版本的一些怪癖和错误
- 将句子拆分为多个语音以使其听起来更自然,尤其是对于旧版本的Chrome(可以禁用)
- 引发特定异常:如果将具有不兼容值的参数传递给任何方法,将引发显式异常
在Chrome,Opera和Safari(包括ios8和ios9设备)中工作。在 iPad 和 Android 上成功测试。
npm地址:www.npmjs.com/package/spe...
js
//安装
npm install speak-tts
js
<script setup lang="ts">
import { ref, onMounted } from 'vue'
// 引入
import Speech from 'speak-tts'
const speech :any = ref(null)
const speechInit = () => {
speech.value = new Speech()
speech.value.setLanguage('zh-CN')
speech.value.init().then(() => {
console.log('语音播报初始化完成')
})
}
//播放按钮
const playSpeak = () => {
speech.value
.speak({
text: '收款2000000元',
listeners: {
//开始播放
onstart: () => {
console.log('Start utterance')
},
//判断播放是否完毕
onend: () => {
console.log('End utterance')
},
//恢复播放
onresume: () => {
console.log('Resume utterance')
}
}
})
.then(() => {
console.log('播报完成')
})
}
onMounted(() => {
speechInit()
})
</script>
<template>
<div>speak-tts</div>
<button @click="playSpeak">播放</button>
</template>
以上的两种方式在PC端盒ISO端都可以用,在Android端可能适配不可用。
下一节,文字可以转语音,那语音如何转成文字呢?
