vue 添加腾讯云语音识别指令

发布于:2025-03-14 ⋅ 阅读:(16) ⋅ 点赞:(0)

 

import voice from './voice/index'

const install = function(Vue) {
  Vue.directive('voice', voice)
}

export default install
import voiceHandler from "./voiceHandler"

export default {
  inserted: function (el, binding) {
    const newElement = document.createElement('span');
    newElement.className = 'el-icon-video-play';
    newElement.addEventListener('click', function () {
      if(this.className === "el-icon-video-play") {
        this.className = "el-icon-video-pause";
        voiceHandler.initVoice(el, binding.value);
      }else {
        this.className = "el-icon-video-play";
        voiceHandler.stopRecording();
      }
      
    });
    el.parentNode.insertBefore(newElement, el.nextSibling);
  }
}
import WebAudioSpeechRecognizer from './speechrecognizer'
import config from './config'

export default {
  el: null,
  bindingVal: null,
  webAudioSpeechRecognizer: null,
  result: null,
  initVoice(el, bindingVal) {
    this.el = el;
    this.bindingVal = bindingVal;
    this.result = '';
    this.startRecording();
  },

  startRecording() {
    this.webAudioSpeechRecognizer = new WebAudioSpeechRecognizer({
      // 用户参数
      secretid:  config.secretId,
      secretkey: config.secretKey,
      appid: config.appId,
      engine_model_type : '16k_zh', // 因为内置WebRecorder采样16k的数据,所以参数 engineModelType 需要选择16k的引擎,为 '16k_zh'
    });
    // 开始识别
    this.webAudioSpeechRecognizer.OnRecognitionStart = (res) => {
      console.log('开始识别', res);
    };
   
    // 识别变化时
    this.webAudioSpeechRecognizer.OnRecognitionResultChange = (res) => {
      console.log('识别变化时', res);
      this.result += res.result.voice_text_str;
    };
  
    // 识别结束
    this.webAudioSpeechRecognizer.OnRecognitionComplete = (res) => {
      console.log('识别结束', res);
    };
    // 识别错误
    this.webAudioSpeechRecognizer.OnError = (res) => {
      console.log('识别失败', res)
    };
    this.webAudioSpeechRecognizer.start(); // 开始录音并识别语音
  },
  stopRecording() {
    console.log('停止识别')
    if (this.webAudioSpeechRecognizer) {
      this.webAudioSpeechRecognizer.stop(); // 停止录音并结束识别过程
      this.el.value = this.result; // 将识别结果赋值给输入框
      this.result = ''; // 清空识别结果
    }
  }
}