SpeechSynthesisUtterance
**SpeechSynthesisUtterance
**是HTML5中新增的API,用于将指定文字合成为对应的语音.也包含一些配置项,指定如何去阅读(语言,音量,音调)等
属性
属性 | 解释 |
---|
pitch | 获取并设置话语的音调(值越大越尖锐,越低越低沉) |
rate | 获取并设置说话的速度(值越大语速越快,越小语速越慢) |
volume | 获取并设置说话的音量 |
lang | 设置播放语言类型 |
text | 语音播放内容 |
voice | 获取并设置说话的声音 |
example
let speech = new SpeechSynthesisUtterance();
speech.pitch = 1;
speech.rate = 1.5;
speech.volume = 10;
speech.lang = "zh-CN";
speech.text = text
事件
事件 | 解释 |
---|
onboundary | 字词边界事件 |
onend | 语音结束事件 |
onerror | 语音错误事件 |
onmark | 语音标记事件 |
onpause | 语音暂停事件 |
onresume | 语音恢复事件 |
onstart | 语音开始事件 |
example
speech.onboundary = () => {
}
speech.onerror = () => {
}
speech.onmark = () => {
}
speech.onstart = (a, b, c) => {
console.log(a, b, c, "a,b,c")
if (func) {
func(params, index)
}
}
speech.onpause = () => {
}
speech.onresume = () => {
}
speech.onend = () => {
}
SpeechSynthesis
SpeechSynthesis
接口是语音服务的控制接口;它可以用于获取设备上关于可用的合成声音的信息,开始、暂停语音,或除此之外的其他命令
属性
属性 | 解释 |
---|
paused | 处于暂停状态时为true |
pending | 当语音播放队列到目前为止保持没有说完的语音时为true |
speaking | 当语音谈话正在进行的时候为true |
example
speak(params, index = 0) {
let [text, ...residue] = params
if (text) {
if (typeof text === "string") {
window.speechSynthesis.speak(this.speech(text))
} else {
let { text: str, hook } = text
window.speechSynthesis.speak(this.speech(str, hook, index, text))
}
}
if (residue.length > 0) {
if (typeof text === "string") {
this.speak(residue)
} else {
this.speak(residue, index + 1)
}
}
}
pause() {
window.speechSynthesis.pause();
}
resume() {
window.speechSynthesis.resume();
}
cancel() {
window.speechSynthesis.cancel();
}
代码封装实现
class Voice {
constructor() {
}
speech(text, func, index, params) {
let speech = new SpeechSynthesisUtterance();
speech.pitch = 1;
speech.rate = 1.5;
speech.volume = 10;
speech.lang = "zh-CN";
speech.text = text
speech.onboundary = () => {
}
speech.onerror = () => {
}
speech.onmark = () => {
}
speech.onstart = (a, b, c) => {
console.log(a, b, c, "a,b,c")
if (func) {
func(params, index)
}
}
speech.onpause = () => {
}
speech.onresume = () => {
}
speech.onend = () => {
}
return speech
}
speak(params, index = 0) {
let [text, ...residue] = params
if (text) {
if (typeof text === "string") {
window.speechSynthesis.speak(this.speech(text))
} else {
let { text: str, hook } = text
window.speechSynthesis.speak(this.speech(str, hook, index, text))
}
}
if (residue.length > 0) {
if (typeof text === "string") {
this.speak(residue)
} else {
this.speak(residue, index + 1)
}
}
}
pause() {
window.speechSynthesis.pause();
}
resume() {
window.speechSynthesis.resume();
}
cancel() {
window.speechSynthesis.cancel();
}
}
export default Voice