audio.js
/*
* @Autor: zhanggenyuan
* @Date: 2021-11-09 17:40:51
* @Description:
*/
/*
* @Autor: lycheng
* @Date: 2020-01-13 16:12:22
*/
/**
* Created by iflytek on 2019/11/19.
*
* 在线语音合成调用demo
* 此demo只是一个简单的调用示例,不适合用到实际生产环境中
*
* 在线语音合成 WebAPI 接口调用示例 接口文档(必看):https://www.xfyun.cn/doc/tts/online_tts/API.html
* 错误码链接:
* https://www.xfyun.cn/doc/tts/online_tts/API.html
* https://www.xfyun.cn/document/error-code (code返回错误码时必看)
*
*/
// 1. websocket连接:判断浏览器是否兼容,获取websocket url并连接,这里为了方便本地生成websocket url
// 2. 连接websocket,向websocket发送数据,实时接收websocket返回数据
// 3. 处理websocket返回数据为浏览器可以播放的音频数据
// 4. 播放音频数据
// ps: 该示例用到了es6中的一些语法,建议在chrome下运行
// import {downloadPCM, downloadWAV} from 'js/download.js'
import CryptoJS from 'crypto-js'
import TransWorker from './transcode.worker'
// import VConsole from 'vconsole'
import { Base64 } from 'js-base64'
// import './index.css'
let transWorker = new TransWorker()
//APPID,APISecret,APIKey在控制台-我的应用-语音合成(流式版)页面获取
const APPID = 'xxx'
const API_SECRET = 'xxx'
const API_KEY = 'xxx'
function getWebsocketUrl() {
return new Promise((resolve, reject) => {
var apiKey = API_KEY
var apiSecret = API_SECRET
var url = 'wss://tts-api.xfyun.cn/v2/tts'
var host = location.host
var date = new Date().toGMTString()
var algorithm = 'hmac-sha256'
var headers = 'host date request-line'
var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/tts HTTP/1.1`
var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
var signature = CryptoJS.enc.Base64.stringify(signatureSha)
var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
var authorization = btoa(authorizationOrigin)
url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
resolve(url)
})
}
const TTSRecorder =class {
constructor({
speed = 30,
voice = 50,
pitch = 50,
voiceName = 'xiaoyan',
appId = APPID,
text = '',
tte = 'UTF8',
defaultText = '请输入您要合成的文本',
} = {}) {
this.speed = speed
this.voice = voice
this.pitch = pitch
this.voiceName = voiceName
this.text = text
this.tte = tte
this.defaultText = defaultText
this.appId = ap