小程序-微信同声传译

需求

小程序录制声音,翻译成中文。
小程序组件地址:链接: https://mp.weixin.qq.com/wxopen/pluginbasicprofile?action=intro&appid=wx069ba97219f66d99&token=&lang=zh_CN.

微信同声传译插件是微信自研的语音输入,文本翻译等功能的插件封装,用于提供给第三方小程序调用。
微信面对面翻译小程序完全使用此小程序插件实现。开源地址:
链接: https://github.com/Tencent/Face2FaceTranslator.

小程序代码

使用前,需要在小程序设置中添加第三方插件“微信同声传译”

插件说明:链接: https://developers.weixin.qq.com/community/develop/doc/0004aa70d609e099c1d671b2a56009.

app.json 引入插件

"plugins": {
    "WechatSI": {
      "version": "0.0.6",
      "provider": "wx069ba97219f66d99"
    }
  },

**app.js 权限询问(可写在其他页面中) **

  // 权限询问
  getRecordAuth: function () {
    wx.getSetting({
      success(res) {
        console.log("succ")
        console.log(res)
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success() {
              // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
              console.log("succ auth")
            }, fail() {
              console.log("fail auth")
            }
          })
        } else {
          console.log("record has been authed")
        }
      }, fail(res) {
        console.log("fail")
        console.log(res)
      }
    })
  },
  onHide: function () {
    wx.stopBackgroundAudio()
  },

** 正文使用 **

1, 获取应用实例
const app = getApp();
2, 引入插件
const plugin = requirePlugin(“WechatSI”);
3,获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager()

data:{
    // 文字题内容
    content: '',
    // 音频临时文件地址
    audioTempFilePath: '',
}

onLoad: function (options) {
    // 微信同步传译
    that.initRecord();

    // 授权语音
    app.getRecordAuth();
  },

  /** 音频开始录制 */
  startAudioRecording: function () {
    let that = this;
    manager.start(); // 语音识别开始
  },

  /** 音频结束录制 */
  endAudioRecording: function () {
    let that = this;
    manager.stop(); // 语音识别结束
  },
  /**
   * 初始化语音识别回调
   */
  initRecord: function () {
    let that = this;

    //有新的识别内容返回,则会调用此事件
    manager.onRecognize = (res) => {
      that.setData({
        content: res.result,
      });
    };

    // 识别结束事件
    manager.onStop = (res) => {
      let text = res.result;
      if (text == '') {
        return $.failMsg("音频识别失败,请输入内容");
      }

      that.setData({
        audioTempFilePath: res.tempFilePath,
      });
    };

    // 识别错误事件
    manager.onError = (res) => {
      $.hideLoading();
      return $.failMsg("音频识别失败,请输入内容");
    };
  },

你可能感兴趣的:(小程序)