使用百度語音介面,實現文字轉化成語音播放
<!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>