code.txt 1.51 KB
const hostUrl = "wss://iat.cn-huabei-1.xf-yun.com"; // 注意多语种识别,也支持中文音频
const appid = "8f15a14c"; //在控制台-我的应用获取
const apiSecret = "MDg2NjUyZWE4YmQyZjNiYjg0MzkyOTUw"; // 在控制台-我的应用获取
const apiKey = "6fd90716018d3deace621bee33bda747"; // 在控制台-我的应用获取

function getAuthUrl(){
    let date = new Date().toUTCString()
    let request_line = 'GET /v1 HTTP/1.1'

    let signature_origin = 'host: '+ hostUrl +'\ndate: '+ date +'\n'+ request_line
    let signature_sha = CryptoJS.HmacSHA256(signature_origin , apiSecret)
    let signature = CryptoJS.enc.Base64.stringify(signature_sha)

    let authorization_origin = 'api_key='+apiKey+', algorithm="hmac-sha256", headers="host date request-line", signature='+signature
    let authorization = window.btoa(authorization_origin)

    return 'wss://iat.cn-huabei-1.xf-yun.com/v1?authorization='+authorization+'&date='+encodeURIComponent(date)+'&host=iat.cn-huabei-1.xf-yun.com'
}


let wssUrl = getAuthUrl()
console.log(wssUrl)
const ws = new WebSocket(wssUrl)

ws.onopen = function(event) {
    console.log('连接已打开');
    ws.send('你好,服务器!'); // 发送消息到服务器
};

ws.onmessage = function(event) {
    console.log('从服务器收到消息: ', event.data); // 显示接收到的消息
};

ws.onerror = function(event) {
    console.error('WebSocket错误: ', event); // 显示错误信息
};

ws.onclose = function(event) {
    console.log(event)
    console.log('连接已关闭');
};