场景:
speak-tts 文字转换语音的使用播放、暂停、恢复
安装
npm install speak-tts
引入
import Speech from ‘speak-tts’
需求:
1.多条播报内容需要一条一条的播报 一进入页面就开始播报(数组的形式 后台返回)
2.暂停之后 在点击播放从头开始播放
3.可以选择是否重复播放
<template>
<i class="el-icon-video-pause" @click="paused()">暂停</i>
<i class="el-icon-video-play" @click="goahead()" >播放</i>
<i class="el-icon-video-play" @click="isLoopPlay()" >是否重复播放</i>
</template>
<script>
import Speech from 'speak-tts'
data () {
return {
speech:null,
dataList:['播报内容1',.......],//需要播报的内容
isStopPlay:false,//是否停止播放
currentIndex:0,//默认当前播放的是第一条
isLoop:true,//是否循环播放 默认循环播放
}
},
mounted(){
this.SpeechInit()
},
methods:{
init(){
this.play(this.dataList[this.currentIndex])
},
SpeechInit(){
this.speech = new Speech()
this.speech.setLanguage('zh-CN')
this.speech.init().then(()=>{
this.init()
})
},
//播放按钮
play(word){
this.speech.speak({
text:word,
listeners: {
//开始播放
onstart: () => { console.log("Start utterance")},
//判断播放是否完毕
onend: () => {
//没有点击暂停播放
if(!isStopPlay){
this.currentIndex++
//如果播放结束了 并且是最后一条的时候 判断是否需要循环播放
if(this.currentIndex> this.dataList.lenght && this.isLoop) {
this.currentIndex=0
}
this.play(this.dataList(this.currentIndex)
}
},
//恢复播放
onresume: () => { console.log("Resume utterance") },
},
}).then(()=>{console.log("读取成功")})
},
//暂停
paused() {
this.isStopPlay=true
this.speech.pause();
//初始化为第一条 删除speech 并赋值为null
this.currenIndex=0
this.speech.cancel()
this.speech=null
},
//暂停之后 在点击播放
goahead() {
this.isStopPlay=false
this.SpeechInit()
},
isLoopPlay(){
this.isLoop=!this.isLoop
}
},
//离开页面取消语音
destroyed() {
this.speech.cancel();
},
</script>