UNIAPP发布小程序调用讯飞在线语音合成+实时播报
语音合成能够将文字转化为自然流畅的人声,提供100+发音人供您选择,支持多语种、多方言和中英混合,可灵活配置音频参数。广泛应用于新闻阅读、出行导航、智能硬件和通知播报等场景。
在当下大模型火爆的今日,语音交互页离不开语音合成的加入。
源码如下:
<template>
<view style="padding: 40rpx;">
<input v-model="tts_text" style="border: 1px solid gainsboro;" />
<button @click="startTts" type="primary" style="margin-top: 20px;">语音合成</button>
</view>
</template>
<script>
// 引入工具包
import * as base64 from "base-64"
import CryptoJS from '../../static/js_util/crypto-js.js'
import * as utf8 from "utf8"
import {
Buffer
} from 'buffer'
export default {
data() {
return {
// 讯飞开放平台获取
wssTask: "", // ws连接任务
url: "wss://tts-api.xfyun.cn/v2/tts",
host: "tts-api.xfyun.cn",
sub: "/v2/tts",
appid: "",
api_secret: "",
api_key: "",
tts_text: "", //合成文本
vcn: "xiaoyan", // 发音人
buff: [],
innerAudioContext: uni.createInnerAudioContext(),
}
},
methods: {
async startTts() {
this.buff = []
let myUrl = await this.getWebSocketUrl();
let realThis = this;
this.socketTask = uni.connectSocket({
url: myUrl,
method: 'GET',
success: res => {
console.log(res, "ws成功连接...", myUrl)
}
})
realThis.socketTask.onError((res) => {
console.log("连接发生错误", res)
})
// 发送合成参数
realThis.socketTask.onOpen((res) => {
console.info("wss的onOpen成功执行...", res)
// 第一帧..........................................
console.log('open成功...')
let params = {
"common": {
"app_id": realThis.appid
},
"business": {
"aue": "lame",
"sfl": 1,
"tte": "UTF8",
"ent": "intp65",
"vcn": realThis.vcn,
"pitch": 50,
"speed": 50
},
"data": {
"status": 2,
"text": Buffer.from(realThis.tts_text).toString('base64')
}
};
// 发送数据
});
// 接受到消息时
realThis.socketTask.onMessage((res) => {
console.log('收到API返回的内容:', res.data);
let res_data = JSON.parse(res.data)
// console.log("我打印的"+JSON.stringify(res_data.data))
// 解码音频数据
let audioData = res_data.data.audio;
console.log("我打印的" + JSON.stringify(audioData))
realThis.buff.push(audioData)
if (res_data.data.status == 2) { // 仅合成完毕一次请求播放
realThis.playAudio(0); //开始播放音频
//状态为2才表示合成结束,需要合并
realThis.socketTask.close({
success(res) {
console.log('ws关闭成功---正常关闭', res)
},
fail(err) {
console.log('关闭失败', err)
}
})
}
})
},
// 播放音频
playAudio(cur) {// 可以模拟实时播报
},
// 鉴权
getWebSocketUrl() {
return new Promise((resolve, reject) => {
// 请求地址根据语种不同变化
var url = this.url;
var host = this.host;
var apiKeyName = "api_key";
var date = new Date().toGMTString();
var algorithm = "hmac-sha256";
var headers = "host date request-line";
var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${this.sub} HTTP/1.1`;
var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.api_secret);
var signature = CryptoJS.enc.Base64.stringify(signatureSha);
var authorizationOrigin =
`${apiKeyName}="${this.api_key}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
var authorization = base64.encode(authorizationOrigin);
url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;
// console.log(url)
resolve(url); // 主要是返回地址
});
}
}
}
</script>
<style>
</style>