js tts 语音播报 百度公开接口
<!DOCTYPE html> <html lang="en"> <head> </head> <meta charset="UTF-8"> <title>Document</title> <body> <div> <p id="Text"></p> <input type="button" onclick="doTTS()" value="播放"> <input type="button" onclick="voiceBroadcast()" value="播放2"> <input type="button" onclick="speckText2()" value="播放3"> </div> <div id="box"> </div> </body> <script> function voiceBroadcast(){ var text = "你说的话我没听清,请再说一遍吧!!!"; var url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&cuid=baike&ctp=1&pdt=301&vol=9&rate=32&per=0&text=" + encodeURI(text); // baidu文字转语音 //var url = "http://tts.baidu.com/text2audio?cuid=baike&lan=ZH&ctp=1&pdt=301&vol=9&rate=32&per=0&tex=" + encodeURI(text); var voiceContent = new Audio(url); voiceContent.src = url; voiceContent.play(); } function doTTS() { var box = document.getElementById('box'); var Audio = document.getElementById('audio_id'); var ttsText = document.getElementById('Text').innerHTML; // 播报出座位号 var msg="10" var str = '<audio id="audio_id" autoplay="autoplay"><source src="http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=5&text=你的座位号为${msg}号" type="audio/mpeg"></audio>'; box.innerHTML = str; var playPromise = Audio.play(); if (playPromise !== undefined) { playPromise.then(_ => { Audio.pause(); }) .catch(error => { }); } } function speckText(str){ var str = "你说的话我没听清,请再说一遍吧!!!"; //var request= new URLRequest(); //var url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&text=" + encodeURI(str); // baidu var url = "http://translate.google.cn/translate_tts?ie=UTF-8&tl=zh-CN&total=1&idx=0&textlen=19&prev=input&q=" + encodeURI(str); // google //request.url = encodeURI(url); // request.contentType = "audio/mp3"; // for baidu //request.contentType = "audio/mpeg"; // for google var n = new Audio(url); n.src = url; n.play(); // $("...").play(); // var sound = new Sound(request); // sound.play(); } function speckText2(str){ var msg = '测试语音的,你说的话我没听清,请再说一遍吧'; var url = "http://tts.baidu.com/text2audio?cuid=baike&lan=ZH&ctp=1&pdt=301&vol=9&rate=32&per=0&tex=" + encodeURI(msg); var n = new Audio(url); n.src = url; n.play(); } </script> <html>
注意:
目前测试发现语音发音的不同点
var url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&cuid=baike&ctp=1&pdt=301&vol=9&rate=32&per=0&text=" + encodeURI(text); //var url = "http://tts.baidu.com/text2audio?cuid=baike&lan=ZH&ctp=1&pdt=301&vol=9&rate=32&per=0&tex=" + encodeURI(text);
text:声音低沉 偏男音
tex:声音偏女音