准备工作

Node.js环境
你已经有了一个基于oicq的QQ群机器人,如果没有请看我前面的文章,有现成的项目,git即可
申请一个百度开发者账号,创建语音技术的开发应用API Key和Secret Key

安装依赖

npm install baidu-aip-sdk
# or
# yarn add baidu-aip-sdk

创建调用服务

var AipSpeechClient = require("baidu-aip-sdk").speech;

// 设置APPID/AK/SK
var APP_ID = "你的 App ID";
var API_KEY = "你的 Api Key";
var SECRET_KEY = "你的 Secret Key";

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

var fs = require('fs'); //调用fs

引入至群聊机器人

安装依赖,3个依赖ffmpeg、build tools、wx-voice参考链接
//监听群聊
client.on('message.group', (data)=> {
    // console.log(data);
    const msg = { //赋值
        fromGroup: data.group_id,
        fromAccount: data.sender.user_id,
        nickname: data.sender.nickname,
        message: data.raw_message,
        messageType: data.message[0].type,
        atme: data.atme,
        groupName: data.group_name,
        sendTime: data.time
    };
    //触发条件,聊天中有语音合成即触发
    if (msg.message.indexOf('语音合成') > -1) {
    // 语音合成, 附带可选参数
    // spd 语速,取值0-9,默认为5中语速
    // per 发音人选择, 0为女声,1为男声,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女
    client.text2audio('msg.message', {spd: 0, per: 4}).then(function(result) {
        if (result.data) {
            fs.writeFileSync('tts.mpVoice.mp3', result.data);
        } else {
            // 服务发生错误
            console.log(result)
        }
    }, function(e) {
            // 发生网络错误
            console.log(e)
    });
    // Initialize
    const WxVoice = require('wx-voice');
    var voice = new WxVoice();

    // Error handler
    voice.on("error", (err) => console.log(err));

    // Decode MP3 to silk
    voice.encode(
        "tts.mpVoice.mp3", "output.silk", { format: "silk" },
        (file) => console.log(file));

    //事实上,你需要在这里添加一个延时或者sleep,保证执行完转换后再输出

    // Output: "/path/to/output.silk"
    ai = [
        segment.at(msg.fromAccount),
        segment.record(output.silk),
    ];
    client.sendGroupMsg(msg.fromGroup, ai);
    }
}

测试

请输入图片描述

最后修改:2021 年 08 月 13 日
如果觉得我的文章对你有用,请随意赞赏