☞:官方文檔
☞:網頁示例
具體步驟:
1.通過 socket.io 接收后端傳過來的數據。
2.判斷是否在播放聲音。 如果沒有則直接獲取百度 token 播放聲音
3.如果有,則存入數組。聲音播放結束后,播放數組中的數據並且移除將要播放的數據
項目代碼(注意,代碼有刪減僅供參考):
<template> <div> <div class="app"> <div id="bdtts_div_id"> <audio ref="audio" id="tts_autio_id" :src="audioSrc" autoplay="autoplay" @canplay="playing()" @ended="ending()"> </audio> </div> </div> </div> </template> <script> export default { data() { return { audioSrc: '', orderArr: [], isPlay: false } }, methods: { playing() { // 開始播放聲音 }, ending() {
// 聲音播放結束 console.log('audio end'); var arr = this.orderArr; console.log(this.orderArr) if (arr.length > 0) { this.isPlay = true; var data = arr[0]; this.orderArr.splice(0,1); this.axios.get('baidu', { params: { //請求參數 } }).then((res) => { var str = '' if('wx' == data.type) { str = '微信支付' } else if('zfb' == data.type) { str = '支付寶支付' } str = str + data.message + '元'; this.audioSrc = 'http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=15378723&tok=' + res.data.access_token + '&tex=' + str + '&vol=15&per=0&spd=5&pit=5&aue=3'; this.$refs.audio.play() }) } else { this.isPlay = false; } } }, created: function() { this.$options.sockets.chat = (data) => { console.log(data);
// data: {id: 4, message: 44, type: "wx", order: "v3TYbgt1ea1551428506775"}
if(data.id == this.$route.query.id) { /** * 1.添加進數組中 * 2.判斷是否在播報 * 3.如果沒有在播報---播放提醒 * 4.如果有在播放---播放結束之后,移除已播放過的內容 */ if(this.isPlay == false) { this.isPlay = true; this.axios.get('baidu', { params: { //請求參數 } }).then((res) => { var str = '' if('wx' == data.type) { str = '微信支付' } else if('zfb' == data.type) { str = '支付寶支付' } str = str + data.message + '元'; this.audioSrc = 'http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=15378723&tok=' + res.data.access_token + '&tex=' + str + '&vol=15&per=0&spd=5&pit=5&aue=3'; this.$refs.audio.play() }) } else { console.log('存入數據') this.orderArr.push(data); } } } } } </script> <style scoped> .app { margin-top: 200px!important; margin-left: 33px!important; } </style>