💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 一、调用百度的播报功能 ~~~ function speakText(text){ var url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text="+encodeURI(text); var audio = new Audio(url); audio.src = url; audio.play(); } speakText('hello world ~'); ~~~ #### 1、逐条播放示例: ~~~ var audio = new Audio(), ttsArr = ['你好,我是一个中国人!', 'hello world'], ttsEnd = false; function tts(text) { if(text) { ttsEnd = true; var url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text="+encodeURI(text); // audio.muted = true; audio.src = url; setTimeout(function() { // audio.removeAttribute('muted'); audio.play(); audio.onended = function() { if(ttsArr.length) { tts(ttsArr.shift()); } ttsEnd = false; } }); } } tts(ttsArr.shift()); setTimeout(function() { ttsArr.push('哈哈哈'); if(!ttsEnd) { tts(ttsArr.shift()); } }, 1000); setTimeout(function() { ttsArr.push('呵呵'); if(!ttsEnd) { tts(ttsArr.shift()); } }, 1500); setTimeout(function() { ttsArr.push('孙悟空', '猪八戒'); if(!ttsEnd) { tts(ttsArr.shift()); } }, 1000); ~~~ #### 2、预警铃声 ~~~ // tts var audio = new Audio('./video/music-warning.mp3'), ttsLoop = 0, // 循环次数 ttsEnd = false; // 是否播放结束 function tts() { ttsEnd = true; audio.play(); audio.onended = function() { if(ttsLoop) { tts(); ttsLoop--; } ttsEnd = false; } } // 语音告警 $.checkboxFn({ele: '.js-voice-warning'}, function() { var active = $(this).hasClass('active'); if(active) { // 开启 ttsLoop++; audio.play(); } else { // 关闭 audio.pause(); } }); // 初始化判断 if($('.js-voice-warning').hasClass('active')) { tts(); // 播放 } ~~~ 如果初次加载音频播放报错,可以在客户端chrome浏览器修改自动播放策略,地址:[chrome://flags/#autoplay-policy](chrome://flags/#autoplay-policy) ![](https://box.kancloud.cn/8dd912a5f1317c80fddc034bec4ebb25_671x303.png) ## 二、ResponsiveVoice.JS API地址:https://responsivevoice.org/ ~~~ responsiveVoice.speak("hello world", "Chinese Female", {volume: 1}); ~~~ > 功能比较齐全,不过目前只在firefox浏览器可以使用 ## 三、jQuery.speech 示例下载地址:https://github.com/wenco/speech ~~~ <div id="Result">hello world ~</div> <script src="js/jQuery/jQuery-2.1.4.min.js"></script> <script src="js/speech/jQuery.speech.min.js"></script> <script> $('#Result').speech({ "speech": true, "speed": 1, "bg": "./images/speech.png" }); </script> ~~~