需求背景:本人有一个美食网站(百度搜大厨子美食网),有很多美食食谱,存在用户边做饭边看食谱,如果能用语音播放食谱,用户就不用一直盯着手机了。
php代码如下:
// 通过百度语音接口文字转语音
$target = $news_content['content'];
$str = htmlspecialchars_decode($target); //str_replace("、",",",$target); //保留顿号
$strr = str_replace(" ", "", $str); // str_replace(' ','',$str);
$strrr = strip_tags($strr);
$text= str_replace(array(" ", " ", " "," ","‌","‍","“","”"), "", $strrr); // match_chinese($strr); // $news_detail['title'];
$file = file_get_contents("http://tts.baidu.com/text2audio?cuid=baiduid&lan=zh&ctp=9&pdt=122&per=0&aue=3&tex=$text");
$filepath="./Data/News/$id.mp3";
//写入mp3文件
if(!file_exists($filepath)){
file_put_contents($filepath,$file);
}
这段php代码可以自动去除空格、html标签、img标签等,只留下中文。
mp3文件保存路径自己设置下,记得添加写入和读取权限。
$id.mp3是为了不同文章生成不同文件,避免前端乱了,file_exists判断是为了避免重复生成,减少服务器压力。
百度语音接口参数设置如下,可设置音量大小、语速、男女声等

html和js代码如下:
<script type="text/javascript">
function fun(){
var myAuto = document.getElementById("myaudio");
// myAuto.play();
if (myAuto.paused) { //判断音乐是否在播放中,暂停状态
myAuto.play(); //音乐播放
} else { //播放状态
myAuto.pause(); //音乐停止
}
}
</script>
<div class="tit">
<audio id="myaudio" preload="auto" src="./Data/News/{$newsdetail.id}.mp3" type="audio/mp3" controls="controls" autostart="false" hidden="true">
</audio>
<h2 style="font-weight: 700">{$newsdetail.title}
<input type="button" onclick="fun()" style="background-image:url(/Application/Mob/Static/images/yuyin.png);background-repeat:no-repeat;background-size:100%;border:none;outline: none;width:20px;background-color: #fff;" />
</h2>
</div>
最终效果见https://www.dachuzi.net/index.php?s=/Mob/News/newsdetail/id/73.html,点击红色小喇叭即可播放,如有疑问可加qq1085788379交流
网友评论