使用百度语音广播开放平台—免费生成语音
网址https://developer.baidu.com/vcast
HTML代码
<div id="bdtts_div_id">
<audio id="tts_audio_id" autoplay="autoplay">
<source id="tts_source_id" src="daohang.mp3" type="audio/mpeg">
<embed id="tts_embed_id" height="0" width="0" src="daohang.wav" type="audio/wav">
</audio>
</div>
JS代码
function audioPlay(inst) {
if (inst==-2){setCurEndTimeAndPlay(2.0,3.6)}
else if (inst==2){setCurEndTimeAndPlay(3.8,5.1)}
else if (inst==0){setCurEndTimeAndPlay(5.6,6.7)}
else if (inst==4){setCurEndTimeAndPlay(7.0,9.1)}
else {setCurEndTimeAndPlay(0.1,1.7)}
}
function setCurEndTimeAndPlay(startTime,endTime){
// 设置当前时间
ttsAudio.currentTime=startTime;
// 播放
ttsAudio.play();
var pausing_function = function(){
if(ttsAudio.currentTime >= endTime) {
ttsAudio.pause();
// remove the event listener after you paused the playback
ttsAudio.removeEventListener("timeupdate",pausing_function);
}
};
ttsAudio.addEventListener("timeupdate", pausing_function);
}
function stop() {
ttsAudio.pause();
}
另外加一个免费的在线文字转语音的JS接口
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>百度地图将文字转化为语音并播放</title>
<!-- 这里调用的是百度文字转语音开放API -->
</head>
<body>
<div>
<input type="text" id="ttsText">
<input type="button" id="tts_btn" onclick="doTTS()" value="播放">
</div>
<div id="bdtts_div_id">
<audio id="tts_audio_id" autoplay="autoplay">
<source id="tts_source_id" src="" type="audio/mpeg">
<embed id="tts_embed_id" height="0" width="0" src="">
</audio>
</div>
<!--<audio controls="controls" height="100" width="100">
<source src="song.mp3" type="audio/mp3" />
<source src="song.ogg" type="audio/ogg" />
<embed height="100" width="100" src="song.mp3" />
</audio>-->
</body>
<script>
// var str="你好啊";
// console.log(typeof str);
function doTTS(ttsText) {
var ttsDiv = document.getElementById('bdtts_div_id');
var ttsAudio = document.getElementById('tts_audio_id');
var ttsText= document.getElementById('ttsText').value;
console.log(ttsText);
// 文字转语音
ttsDiv.removeChild(ttsAudio);
var au1 = '<audio id="tts_audio_id" autoplay="autoplay">';
var sss = '<source id="tts_source_id" src="http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&per=3&spd=5&text=' + ttsText + '" type="audio/mpeg">';
var eee = '<embed id="tts_embed_id" height="0" width="0" src="http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&per=3&spd=5&text=' + ttsText + '">';
var au2 = '</audio>';
ttsDiv.innerHTML = au1 + sss + eee + au2;
ttsAudio = document.getElementById('tts_audio_id');
ttsAudio.play();
}
/*
代码中改变传参可更改配置:
lan=zh(语言zh:中文;en:英文;fr:法文;)
ie=UTF-8(字符集)
per=3(每3个字符停顿)
spd=5(语音播放速度,数字越大越快0-15)
text=“”(需要转换的文字)*/
/* var msg = new SpeechSynthesisUtterance("hello everyone");
console.log(msg);
window.speechSynthesis.speak(msg);*/
</script>
</html>
大概思路就是这些,如果需要自行加以更改即可使用。
记录一下。