当前位置:   article > 正文

vue2实现了网页录音并调用阿里云websocket接口,把语音转成文字功能_vue语音识别转文字

vue语音识别转文字

vue2实现了网页录音并调用阿里云websocket接口,把语音转成文字功能

上代码:

<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, // 采样位数,支持 816,默认是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>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/39598?site
推荐阅读
相关标签
  

闽ICP备14008679号