APP——语音识别

//HubuilderX 语音识别插件配置: https://ask.dcloud.net.cn/article/35059

封装的工具类speech.js

let instance = null;

class Speech {
  constructor() {
    if (!instance) {
      instance = this;
    }
    return instance;
  }
  // 初始化 语音识别
  initRecognize() {
    plus.speech.addEventListener('start', () => {
      // console.log('开始语音识别');
      this._start();
    }, false);
    plus.speech.addEventListener('volumeChange', ({
      volume
    }) => {
      // console.log('音量变化', volume);
      this._volumeChange({
        volume
      })
    }, false);
    plus.speech.addEventListener('recognizing', ({
      partialResult
    }) => {
      // console.log('临时语音识别结果', partialResult);
      this._recognizing({
        partialResult
      })
    }, false);
    plus.speech.addEventListener('recognition', ({
      result
    }) => {
      // console.log('最终语音识别', result);
      this._recognition({
        result
      })
    }, false);
    plus.speech.addEventListener('end', () => {
      // console.log('结束语音识别');
      this._end()
    }, false);
    plus.speech.addEventListener('error', ({
      code,
      message
    }) => {
      console.log('语音识别错误', code, message);
      this._error({
        code,
        message
      })
    }, false);
  }
  // 开始语音识别
  start({
    start = () => {},
    volumeChange = () => {},
    recognizing = () => {},
    recognition = () => {},
    end = () => {},
    error = () => {},
  }) {
    this._start = start;
    this._volumeChange = volumeChange;
    this._recognizing = recognizing;
    this._recognition = recognition;
    this._end = end;
    this._error = error;
    const options = {
      engine: 'baidu', // 百度:baidu  讯飞:iFly
      continue: true,
      // userInterface: false
    };
    plus.speech.startRecognize(options);
  }
  stop() {
    plus.speech.stopRecognize();
  }
}

export default new Speech();

import Speech from '@/Speech.js';
Vue.prototype.$speech = Speech;

引用:

 <m-button class="demo-btn" type="primary" @click.native="startRecognize">

// 开始识别
    startRecognize() {
      this.$speech.start({
        start: () => {
          this.saveLog('开始语音识别');
        },
        volumeChange: ({ volume }) => {
          this.saveLog('音量变化: ' + volume);
        },
        recognizing: ({ partialResult }) => {
          this.saveLog('临时语音识别结果: ' + partialResult);
        },
        recognition: ({ result }) => {
          this.saveLog('最终语音识别: ' + result);
        },
        end: () => {
          this.saveLog('结束语音识别');
        },
        error: ({ code, message }) => {
          this.saveLog('语音识别错误: ' + code + ',' + message);
        }
      });
    },

saveLog(message) {
      this.logs.unshift(message);
    }

发布了44 篇原创文章 · 获赞 15 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Sunshine0508/article/details/104751055