百度语音合成语音文件并在网站中展示
项目背景:
百度语音合成api
pbootcms(sqlite3版本),mysql或者其他网站可以适当的修改一下流程也可以
数据库操作文件SQLite.php
<?php //sqlite路径 define("dbfile","../data/106aa56d9c6bda96a8e0829ace2466a6.db"); class SQLiteDB extends SQLite3 { function __construct($file) { $this->open($file); } } //根据sql查询表 function query($db,$sql){ $ret = $db->query($sql); return $ret; } function close($db){ $db->close(); } //根据id获取数据备注信息 function getDesc($id){ $db = new SQLiteDB(dbfile); $sql = "SELECT description from ay_content where id = ".$id; $ret = query($db,$sql); $row = $ret->fetchArray(SQLITE3_ASSOC); return ($row['description']); } ?>
百度语音合成路口文件:
<?php include("../include/SQLite.php"); require_once 'AipSpeech.php'; // 你的 APPID AK SK const APP_ID = '百度id'; const API_KEY = '百度key'; const SECRET_KEY = 'baidu_SECRET'; $itemid=$_GET['id']; //判断文件是否存在,存在的话就不继续了 $filename = $itemid.'.mp3'; //创建文件夹 $dir = "../static/audio"; if(creatDir($dir)){ $filename =realpath($dir) .'\\'. $filename; //echo $filename; } if(!file_exists($filename)){ echo "开始生成音频"; $title = getDesc($itemid); if($title == "" || $title == ' '){ exit(); }else{ echo $title; } $slogn="更多内容请阅读xxx"; $content=$title.$slogn; $client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY); $result = $client->synthesis($content, 'zh', 6, array( 'vol' => 5, )); // 识别正确返回语音二进制 错误则返回json 参照下面错误码 if(!is_array($result)){ file_put_contents($filename, $result); //下面两行配合使用可以输出音频文件 //header('Content-Type: audio/mpeg'); // echo $result; } } function creatDir($dir){ //echo $dir; //要创建的多级目录 $path=$dir; //判断目录存在否,存在给出提示,不存在则创建目录 if (is_dir($path)){ return true; }else{ //第三个参数是“true”表示能创建多级目录,iconv防止中文目录乱码 $res=mkdir(iconv("UTF-8", "GBK", $path),0777,true); if ($res){ return true; }else{ return false; } } } ?>
其中require_once 'AipSpeech.php';是引用百度的文件
音频文件生成目录:
前端新闻模板页:news.html
<!-- 在head中引用jquery--> <script src="/skin/js/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script> <!-- 这里可以放在head中也可以放到bady中--> <script> var id = '{content:id}'; $(function(){ $.ajax({ type: "GET", url: "/speek/index.php", data: {id:id}, dataType: "text", success: function(data){ console.log(data); var audio = '<audio controls="controls">'+ '<source src="/static/audio/{content:id}.mp3" type="audio/mp3" />'+ 'Your browser does not support this audio format.</audio>'; $('.audio_c').append(audio); //audio_c是需要插入的音频位置的类名 } }); }); </script> <!-- 把下面的语句放到需要插入的文件位置上--> <p class="audio_c" style="text-align: center;"></p>
以上内容来源于百科书,可以关注我了解更多.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了