赞
踩
上代码:
<template> <!-- 实现了语音上传翻译成文字 --> <div> <el-button @mousedown.native="handleStart">录音</el-button> <el-button @click="handleEnd()">结束</el-button> <el-button type="primary" @click="handlePlay">播放录音</el-button> <el-row> {{websocket_audio2txt_result_msg}} </el-row> </div> </template> <script> import API from '../../api/api'; import Recorder from 'js-audio-recorder'; // import Recorder from '../../api/recorder_my.js'; // import {HZRecorder} from '../../api/HZRecorder_my.js'; import {dateFtt} from '../../api/tool.js'; export default { //1.必须要声明一个播放器的容器 player就是播放器的容器 data () { return { recorder :Recorder, faq_token:"",//faq的token ,请求接口获取 faq_appkey:"",//faq的appkey ,请求接口获取 websocket_audio2txt_result_msg:"",//音频转文本的结果信息 websock:null,//websocket的 websocket_task_id:"",//websocket 的会话id 整个实时语音识别的会话ID,整个请求中需要保持一致,32位唯一ID。 websocket_audio2txt_complete_b:false,//websocket 语音转文本 一句话是否收集完毕 true:完毕 websocket_audio2txt_time:0,//websocket 语音转文本 一句话收集完毕的时间,用于判断间隔 websocket_audio2txt_complete_time_fuzhi:100,//websocket 语音转文本 判断文本是否收集完毕的阈值 单位毫秒 timer_websocket:null,//websocket的定时器 } }, mounted () { }, created() { // this.recorder = new Recorder(); this.getPermission(); this.getFAQMsg();//获取FAQ的信息 }, beforeDestroy () { }, methods:{ //获取FAQ的信息 getFAQMsg(){ var submit_obj = {}; submit_obj.param = "getToken"; //请求接口 API.FAQServlet(submit_obj).then((res) => { // console.log(res); if (res.recode === 0) { console.log("res.token:"+res.token); this.faq_token = res.token;//faq的token ,请求接口获取 this.faq_appkey = res.appkey;//faq的appkey ,请求接口获取 } }); }, /** * 获取麦克风权限 * */ getPermission(){ Recorder.getPermission().then(() => { // this.$message.success('获取权限成功'); console.log("获取麦克风权限--成功"); }, (error) => { console.log(error); }); }, //停止 handleEnd(){ console.log("handleEnd..."+dateFtt(new Date(),'yyyy-MM-dd hh:mm:ss.S')); // this.recorder.pause();//暂停录音 this.recorder.stop();//关闭录音 //初始化weosocket this.initWebSocket(); //this.websocketSendStop();//连接建立之后发送 StopTranscription指令 }, //播放 handlePlay(){ console.log("handlePlay..."); this.recorder.play();//播放录音 }, // 开始录音 handleStart() { console.log("handleStart..."); //this.initWebSocket(); //初始化weosocket this.websocket_audio2txt_result_msg = "";//置空 //启动录音的控件 this.recorder = new Recorder({ sampleBits:16, // 采样位数,支持 8 或 16,默认是16 sampleRate:16000, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,我的chrome是48000 numChannels: 1,//声道数 // compiling: true,//(0.x版本中生效,1.x增加中) // 是否边录边转换,默认是false }); this.recorder.start(); }, //初始化weosocket initWebSocket(){ console.log("初始化weosocket"); this.websocket_audio2txt_complete_b = false;//websocket 语音转文本 一句话是否收集完毕 true:完毕 this.websocket_audio2txt_time = 0;//websocket 语音转文本 一句话收集完毕的时间,用于判断间隔 //关闭websocket if(this.websock != null){ this.websock.close(); this.websock == null; } // const wsuri = `wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1?token=${this.faq_token}`; const wsuri = `wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1?token=${this.faq_token}`; //连接服务端 this.websock = new WebSocket(wsuri); //指定事件回调 this.websock.onmessage = this.websocketOnMessage; this.websock.onopen = this.websocketOnOpen; this.websock.onerror = this.websocketOnError; this.websock.onclose = this.websocketClose; }, //生成32位随机数 getRandomStrNum() { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 32; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23]; var uuid = s.join(""); return uuid; }, websocketOnOpen(){ //连接建立之后执行send方法发送数据 console.log("向 websocket 发送 链接请求"); this.websocket_task_id = this.getRandomStrNum();//生成新的任务id var message_id = this.getRandomStrNum(); //actions 是首次连接需要的参数,可自行看阿里云文档 let actions = { "header": { "message_id": message_id, "task_id": this.websocket_task_id, "namespace": "SpeechTranscriber", "name": "StartTranscription", "appkey": this.faq_appkey, }, "payload": { "format": "PCM",//音频编码格式,默认是PCM(无压缩的PCM文件或WAV文件),16bit采样位数的单声道。 "sample_rate": 16000, "enable_intermediate_result": true,//是否返回中间识别结果,默认是false。 "enable_punctuation_prediction": true,//是否在后处理中添加标点,默认是false。 "enable_inverse_text_normalization": true, "enable_ignore_sentence_timeout":true,//是否忽略实时识别中的单句识别超时,默认是false。 "enable_words":true,//是否开启返回词信息,默认是false。 "max_sentence_silence":2000,// 语音断句检测阈值,静音时长超过该阈值会被认为断句,参数范围200ms~2000ms,默认值800ms。 } }; this.websocketSend(JSON.stringify(actions)); }, websocketSendStop(){ //连接建立之后发送 StopTranscription指令 console.log("向 websocket 发送 Stop指令"); var message_id = this.getRandomStrNum(); //actions 是首次连接需要的参数,可自行看阿里云文档 let actions = { "header": { "message_id": message_id, "task_id": this.websocket_task_id, "namespace": "SpeechTranscriber", "name": "StopTranscription", "appkey": this.faq_appkey, } }; this.websocketSend(JSON.stringify(actions)); }, websocketOnError(){//连接建立失败重连 console.log("连接建立失败重连"); // this.initWebSocket(); }, websocketOnMessage(e){ //数据接收 const redata = JSON.parse(e.data); if(redata.header.name==='TranscriptionResultChanged'){ console.log('数据接收-返回的数据'+dateFtt(new Date(),'yyyy-MM-dd hh:mm:ss.S'),redata.payload); //websocket 语音转文本 一句话是否收集完毕 true:完毕 this.websocket_audio2txt_complete_b = false; //数据在收集中 }else if(redata.header.name==='SentenceBegin'){ //一句话开始后,就可以启动录音了 }else if(redata.header.name==='TranscriptionStarted'){ console.log("数据接收,开始:",redata); //获取音频信息,并发送 this.getWavAndSend(); }else if(redata.header.name==='SentenceEnd'){ //结束 console.log('数据接收-一句话结束---返回的数据'+dateFtt(new Date(),'yyyy-MM-dd hh:mm:ss.S'),redata.payload); this.websocket_audio2txt_result_msg += redata.payload.result; //websocket 语音转文本 一句话是否收集完毕 true:完毕 this.websocket_audio2txt_complete_b = true; //websocket 语音转文本 一句话收集完毕的时间,用于判断间隔 this.websocket_audio2txt_time = new Date().getTime(); //设置定时器-websocket this.setTimer_websocket(); } }, //获取音频信息,并发送 getWavAndSend(){ // const blob = this.recorder.getWAVBlob(); const blob = this.recorder.getPCMBlob(); var blob_size = blob.size; console.log("获取音频信息,并发送,blob_size:"+blob_size+" "+dateFtt(new Date(),'yyyy-MM-dd hh:mm:ss.S'),blob); var max_blob_size = 3200;//支持1600 或3200 var my_num = blob_size/max_blob_size; my_num = my_num + 1; for(var i=0;i<my_num;i++){ var end_index_blob = max_blob_size*(i+1); if(end_index_blob > blob_size){ end_index_blob = blob_size; } var blob2 = blob.slice(i*max_blob_size,end_index_blob); const newbolb = new Blob([blob2], { type: 'audio/pcm' }) //发送 this.websocketSend(newbolb); } this.websocketSendStop();//发生结束 }, websocketSend(Data){//数据发送 // console.log('websocket 数据发送',Data); //判断是否连接成功,连接成功再发送数据过去 if(this.websock.readyState===1){ this.websock.send(Data); }else{ console.log('websock未连接-------------------'); } }, // eslint-disable-next-line websocketClose(e){ //关闭 // eslint-disable-next-line console.log('websocketClose断开连接'+dateFtt(new Date(),'yyyy-MM-dd hh:mm:ss.S'),e); // this.initWebSocket(); }, //请求接口 req_interface(txt_value){ console.log("请求接口 txt_value:"+txt_value+" "+dateFtt(new Date(),'yyyy-MM-dd hh:mm:ss.S')); }, //设置定时器-websocket setTimer_websocket(){ //销毁定时器 console.log("设置定时器 setTimer_websocket"); // this.clearTimer_websocket(); if(this.timer_websocket == null){ this.timer_websocket = window.setInterval(() => { if(this.websocket_audio2txt_complete_b){ if(new Date().getTime() - this.websocket_audio2txt_time >= this.websocket_audio2txt_complete_time_fuzhi){ //销毁定时器-websocket this.clearTimer_websocket(); //关闭websocket if(this.websock != null){ this.websock.close(); this.websock == null; } //请求接口 this.req_interface(this.websocket_audio2txt_result_msg) } } }, 30)//30毫秒获取一次 } }, //销毁定时器-websocket clearTimer_websocket(){ if(this.timer_websocket != null){ console.log("销毁定时器-websocket 成功"); window.clearInterval(this.timer_websocket);//销毁定时任务 this.timer_websocket = null; } }, } } </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。