老规矩, 先赞后看
1, 基础使用
开始播放, 播放完自动结束
js
window.speechSynthesis.speak(new SpeechSynthesisUtterance('哈哈哈'))
手动结束
js
window.speechSynthesis.cancel()
其他参数
js
let ut = new SpeechSynthesisUtterance('哈哈哈')
ut.xxx
`text` -- 播放的内容, 例如上面的'哈哈哈'
`lang` -- 播放的语言,例如:`zh-cn`
`voiceURI` -- 指定希望使用的声音和服务,字符串。
`volume` -- 音量,区间范围是`0`到`1`,默认是`1`。
`rate` -- 语速,默认值是`1`,范围是`0.1`到`10`,表示语速的倍数,例如`2`表示正常语速的两倍。
`pitch` -- 音调,范围从`0`(最小)到`2`(最大)。默认值为`1`。
暴露的方法
`onstart` -- 语音合成开始时候的回调。
`onpause` -- 语音合成暂停时候的回调。
`onresume` -- 语音合成重新开始时候的回调。
`onend` -- 语音合成结束时候的回调。
其他方法
js
window.speechSynthesis.xxxx
speak() 播放
cancel() 结束
pause() 暂停
resume() 恢复暂停的语音
2, 自定义播放次数
js
function playVoice(text, times = 1) {
let count = 0
const play = () => {
if (count < times) {
let utterance = new SpeechSynthesisUtterance(text)
utterance.onend = () => {
count++
if (count < times) {
setTimeout(() => {
play()
}, 1000)
}
}
window.speechSynthesis.speak(utterance)
}
}
play()
}
playVoice('好好好', 3)
3, 多次播放 方法封装使用
新建speech.js
js
// 定义一个class
class SpeechManager {
constructor() {
this.utterance = null
this.isPlaying = false
this.repeatTimeout = null
}
// 播放语音
speak(text, options = {}) {
const {
repeat = false, // 是否重复播放
repeatDelay = 500 // 重复播放延迟时间(ms)
} = options
// 取消之前的语音
this.cancel()
this.utterance = new SpeechSynthesisUtterance(text)
if (repeat) {
this.utterance.onend = () => {
this.repeatTimeout = setTimeout(() => {
if (this.isPlaying) {
window.speechSynthesis.speak(this.utterance)
}
}, repeatDelay)
}
}
this.isPlaying = true
window.speechSynthesis.speak(this.utterance)
}
// 取消语音播放
cancel() {
this.isPlaying = false
if (this.repeatTimeout) {
clearTimeout(this.repeatTimeout)
this.repeatTimeout = null
}
window.speechSynthesis.cancel()
}
}
// 导出
export default new SpeechManager()
在需要使用的页面里导入
js
import speechManager from '@/util/speech.js'
//某个方法里面需要使用
xxx(){
// 两个字段, 播放的文本和是否重复播放
speechManager.speak('请将身份证放置刷卡区或手动输入证件号', { repeat: true })
}
//某个方法里面结束播放
xxx(){
speechManager.cancel()
}
4, 封装的源码js已经上传, 需要自取 点击前往
没了, 记录一下, 下期再见! END-------------------