百度语音+react+loopback实现语音合成返回播放

1.在百度语音中创建自己的项目,需要拿到APP_ID、API_KEY、SECRET_KEY。

2.loopback端提供接口服务,在./boot目录下新建root.js文件,编写不依赖模型的自定义接口服务,代码如下:

'use strict';

const fs=require('fs')
const AipSpeechServer = require('baidu-aip-sdk').speech;

module.exports = function(server) {
  // Install a `/` route that returns server status
  var router = server.loopback.Router();// 语音合成
  //设置appid/appkey/appsecret
  const APP_ID = "14799027";
  const API_KEY = "2oSvF6rAFnq6hiVowTxM4fkb";
  const SECRET_KEY = "AbyQ8gagqQGauBGOKU9DABsLQOIq5Pwo";

// 新建一个对象,建议只保存一个对象调用服务接口
const client =new AipSpeechServer(APP_ID, API_KEY, SECRET_KEY);

// 语音合成
router.post('/speech', function(req, res, next){
  client.text2audio(
    req.body.text || '你好,百度语音合成测试',
    {
      //cuid: '机器 MAC 地址或 IMEI 码,长度为60以内',
      spd: req.body.spd || '5',//音速
      pit: req.body.pit || '5',//音调
      vol: req.body.vol || '5',//音量
      per: req.body.per || '0'//播音角色
    }
  )
  .then(
    function(res1){
      if(res1.data){
        console.log(res1,'d;');
        fs.writeFileSync('./server/static/tts.audio.mp3', res1.data);

        res.json({
          ret: 0,
          data:{
            path: 'http://192.168.6.12:6001/tts.audio.mp3',//返回小程序调用播放
            audio:'data:audio/wav;base64,' + new Buffer(res1.data).toString('base64') // buffer二进制文件转base64
          },
          msg: ''
        });

      }else{
        // 服务发生错误
        console.log(res1);
        res.json({
          ret: res1.err_no,
          data:{
          },
          msg: res1.err_msg
        });
      }
    }, 
    function(e){
      // 发生网络错误
      console.log(e);
      res.json({
        ret: -100,
        data:{
        },
        msg: '网络错误,请检查网络'
      });
    }
  );
});

  server.use(router);
};

3.前端调用服务接口即可。

let data = {
      text: '请,蒋龙江,到1号诊室就诊。',
      spd: '5',
      pit: '3',
      vol: '8',
      per: '0'
 };
let a = yield axios.post(`/speech`,data);
let n = new Audio();
n.src = a.data.data.audio;
n.play();

这样在浏览器中就能播放了。

百度语音node只支持在线语音库,暂不支持离线。

猜你喜欢

转载自www.cnblogs.com/jlj9520/p/9963295.html