// 全局声明 audio let audio = null; // 实时获取后台返回的 音频流(MP3流)并进行播放 function ttsPlay(params) { return new Promise((resolve, reject) => { axios({ method: 'post', url: 'https://tsn.baidu.com/text2audio?lan=zh&per=4121&cuid=baidu_speech_demo&idx=1&cod=2&lan=zh&ctp=1&pdt=220&aue=3&pit=5&ie=UTF-8&spd=4&tex=' + params, responseType: 'arraybuffer' }).then((response) => { // 将 blob 数据转换成 url let mp3Url = window.URL.createObjectURL(new Blob([response.data])) // 进行音频播放 try { var playCount = 10; //是否已经声明过 if (audio == null) { audio = new Audio(); audio.addEventListener('ended', function() { // alert(playCount) playCount = playCount - 1; if(playCount <= 0) localStorage.setItem('audioEnded', true); else{ setTimeout("audio.play()",1000) } }, false); } if (mp3Url) { audio.src = mp3Url; // audio.multer = true; audio.play(); } } catch (e) {} }).catch((error) => { reject(error); }) }) }