一、前言
前一段时间在项目中需要用到播报文字语音。找到了 HTML 5 有这样的功能。
现在有时间进行总结下。
二、SpeechSynthesis
SpeechSynthesis 接口是语音服务的控制接口。它可以用于获取设备上关于可用的合成声音的信息,
开始、暂停语音,或者别的命令。(MDN)
SpeechSynthesis 是 window 上面的属性,可以直接调用。
属性:
下面的都是只读属性
paused:是否处于暂停状态,返回 Boolean 值
pending:语音播报队列中是否有需要说的语音,返回 Boolean 值
speaking:是否正在进行语音播报(包括暂停状态),返回 Boolean 值
事件:
onvoiceschanged:当 getVoices 返回的 voices 列表改变时触发
方法:
cancel:移除所有语音播报队列中的语音
getVoices:返回当前设备可用的声音列表
pause:暂停语音播报
resume:把对象设置为非暂停状态,如果是暂停就继续
speak:添加一个 utterance 到语音播报队列,会在其他语音播报后播报
三、SpeecheSynthesisUtterance
SpeecheSynthesisUtterance 是语音请求的一个类。需要实例化才可以使用。
它包含语音要阅读的内容以及如何阅读(例如语言、音调、音量等)
属性:
lang:读取或设置当前要阅读的语音
pitch:读取或设置阅读的音调
rate:读取或设置阅读的语速
text:读取或设置阅读的内容
voice:读取或设置阅读的声音(不同的浏览器有不同内置的人声)
volume:读取或设置阅读的音量
事件:
boundary:当阅读到单词或句子的边界时触发
end:当阅读结束时触发
error:当阅读报错时触发
mark:当阅读到 SSML 标记时触发
pause:当阅读暂停时触发
resume:当阅读设置为非暂停时触发
start:开始阅读时触发
上面的事件都是用 addEventListenter 绑定事件,同时也可以用对应的 onEventname 绑定事件
四、示例
上面两个 API 可以满足基本的语音播报需要了,下面就是一个示例
/* input{
width: 500px;
height: 200px;
} */
// 1.获取input框输入的内容
function getValue() {
//定义全局对象
const obj = {
text: "",
lange: "zh-cn",
volume: 1,
rate: 1,
pitch: 1,
};
//点击“播报”按钮
const Dom = document.getElementById("submit");
Dom.onclick = function () {
const value = document.getElementById("input").value;
if (!value) return;
console.log("点击获取内容1", value);
obj.text = value;
speeck(obj);
};
//按下回车键按钮
window.onkeyup = function (e) {
// console.log("e",e);
const value = document.getElementById("input").value;
if (e.keyCode !== 13 || !value) return;
console.log("回车获取内容2", value);
obj.text = value;
speeck(obj);
};
//暂停播报
const suspend = document.getElementById("suspend");
suspend.onclick = function () {
window.plays.pause(); //暂停
};
//恢复播报
const recovery = document.getElementById("recovery");
recovery.onclick = function () {
window.plays.resume(); //恢复
};
//停止播报
const stop = document.getElementById("stop");
stop.onclick = function () {
window.plays.cancel(); //停止
};
//选择语言
const lange = document.getElementById("lange");
lange.onchange = function (v) {
console.log("选择语言", v);
console.log("选择语言-2", v.target.value);
obj.lange = v.target.value;
speeck(obj);
};
//选择音量
const volume = document.getElementById("volume");
volume.onchange = function (v) {
console.log("选择音量", v.target.value);
obj.volume = v.target.value;
speeck(obj);
};
//选择音速
const rate = document.getElementById("rate");
rate.onchange = function (v) {
console.log("选择音速", v.target.value);
obj.rate = v.target.value;
speeck(obj);
};
//选择音色
const pitch = document.getElementById("pitch");
pitch.onclick = function (v) {
console.log("选择音色", v.target.value);
obj.pitch = v.target.value;
speeck(obj);
};
}
//调用执行
getValue();
//2.语音播报
function speeck(data) {
console.log("播报时", data);
//SpeechSynthesisUtterance对象,主要用来构建语音合成实例
window.voice = new window.SpeechSynthesisUtterance();
// 对象合成方法
Object.assign(window.voice, data)
//speechSynthesis对象,主要作用是触发行为,例如读,停,还原
window.plays = window.speechSynthesis;
window.plays.speak(window.voice);
}
好文推荐
发表评论