Node.js+Express+百度语音合成(AipSpeechClient)API
引入模块,实例化接口
// express
let express = require("express");
// 获取baidu语音合成接口
let AipSpeechClient = require("baidu-aip-sdk").speech;
// 导入node文件管理模块
var fs = require("fs");
// 实例化接口
var client = new AipSpeechClient(APP_ID, API_KEY, SECRET_KEY);
- 这里的APP_ID,API_KEY,SECRET_KEY需要自己去获取:
APP_ID: 这是从百度AI开放平台获取的应用ID。API_KEY: 百度API的密钥,用于身份验证。SECRET_KEY: 百度API的密钥secret,也是身份验证的一部分。
实例化服务和静态数据处理,定义接口
中间件和实例化
// 实例化服务器
let app = express();
// 静态服务器中间件设置
app.use(express.static("static"));
定义接口和中间件处理
// 跨域处理中间
app.use((req, res, next) => {
res.append("Access-Control-Allow-Origin", "*");
res.append("Access-Control-Allow-Content-Type", "*");
next();
});
app.get("/", (req, res) => {
res.send("语音合成");
});
app.get("/api/audio", async (req, res) => {
console.log("请求来了");
// 获取get里,text的参数
let text = req.query.text;
// 调用生成音频文件,并且获取音频文件的链接地址
let audioLink = await createAudio(text);
// 以json的形式返回audio地址给前端
res.json({ audioLink });
});
app.listen(8888, () => {
console.log("server start:", "http://localhost:8888");
});
将百度接口调用函数封装
function createAudio(text) {
return new Promise((resolve, reject) => {
client.text2audio(text).then(
function (result) {
// result.data,音频数据写入
if (result.data) {
// 生成当前时间戳
let time = new Date().getTime();
// 同步方式写入文件
fs.writeFileSync(`static/audio/voice${time}.mp3`, result.data);
resolve(`http://localhost:8888/audio/voice${time}.mp3`);
} else {
console.log("文件写入失败");
reject("文件写入失败");
}
},
function (e) {
console.log("接口出错了");
reject(e);
}
);
});
}
调用接口生成音频文件
```
client.text2audio(text).then(
function (result) {
// result.data,音频数据写入
if (result.data) {
// 生成当前时间戳
let time = new Date().getTime();
// 同步方式写入文件
fs.writeFileSync(`static/audio/voice${time}.mp3`, result.data);
} else {
console.log("文件写入失败");
}
},
function (e) {
console.log("接口出错了");
}
);
```