使用百度语音接口,实现文字转化成语音播放
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>百度语音测试</title> </head> <body> <div> <input type="text" id="ttsText"> <input type="button" id="tts_btn" onclick="doTTS()" value="获取新的语音"> <input type="button" id="tts_btns" onclick="zanting()" value="暂停"> <input type="button" id="tts_btns" onclick="jixu()" value="继续/播放"> <input type="button" id="tts_btns" onclick="shichang()" value="时长"> </div> <div id="bdtts_div_id"> <audio id="tts_autio_id" > <source id="tts_source_id" src="https://tsn.baidu.com/text2audio?tex=我喜欢你&lan=zh&per=4&cuid=1&ctp=1&tok=24.71726d18e11bf62415c11e3c2aa88121.2592000.1544946462.282335-14837008" type="audio/mpeg"> <embed id="tts_embed_id" height="0" width="0" src=""> </audio> </div> </body> </html> <script> function zanting() { var ttsAudio = document.getElementById('tts_autio_id'); ttsAudio.pause(); } function jixu() { var ttsAudio = document.getElementById('tts_autio_id'); ttsAudio.play(); } function shichang() { var ttsAudio = document.getElementById('tts_autio_id'); alert(ttsAudio.duration); } function doTTS(){ var ttsDiv = document.getElementById('bdtts_div_id'); var ttsAudio = document.getElementById('tts_autio_id'); var ttsText = document.getElementById('ttsText').value; // 这样为什么替换不了播放内容 /*var ssrcc = 'http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=10&text='+ttsText; document.getElementById('tts_source_id').src=ssrcc;*/ // 这样就可实现播放内容的替换了 ttsDiv.removeChild(ttsAudio); var au1 = '<audio id="tts_autio_id" autoplay="autoplay">'; var sss = '<source id="tts_source_id" src="https://tsn.baidu.com/text2audio?tex='+ttsText+'&lan=zh&per=4&cuid=1&ctp=1&tok=24.71726d18e11bf62415c11e3c2aa88121.2592000.1544946462.282335-14837008" type="audio/mpeg">'; var eee = '<embed id="tts_embed_id" height="0" width="0" src="">'; var au2 = '</audio>'; ttsDiv.innerHTML = au1 + sss + eee + au2; ttsAudio = document.getElementById('tts_autio_id'); ttsAudio.play(); } </script>