微信小程序同声传译开发(语音识别、语音输入转文字)开发教程

1,570 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

微信同声传译插件是微信自研的语音输入,文本翻译等功能的插件封装,用于提供给第三方小程序调用。

1.小程序后台进行配置

在浏览器搜索微信公众平台,微信扫码登录小程序。点击设置->第三方设置->插件管理->添加插件。

image.png

image.png

添加成功后如图:

image.png

2.小程序端开发 截止到5月16日,微信同声传译版本是0.3.4。

2.1在小程序文件app.json中添加插件信息

"plugins": {

"WechatSI": {

    "version": "0.3.4",

    "provider": "wx069ba97219f66d99"

}

},

参照下图,注意和window同级!

image.png

2.2在util.js文件中添加如下代码:

//微信同声传译

var plugin = requirePlugin("WechatSI")

var innerAudioContext = wx.createInnerAudioContext();

innerAudioContext.onError((res) => {

// 播放音频失败的回调

})

function playTTS(text) {

//need to add WXAPP plug-in unit: WechatSI

plugin.textToSpeech({

lang: "zh_CN",

tts: true,

content: text,

success: function (res) {

  log("succ tts", res.filename)

  innerAudioContext.src = res.filename;

  innerAudioContext.play()

},

fail: function (res) {

  log("fail tts", res)

}

})

}

function stopTTS() {

innerAudioContext.stop();

}

module.exports = {

playTTS: playTTS,

stopTTS: stopTTS,

}

2.3在你调用同声传译的目录下,在.js文件中添加如下代码:

var plugin = requirePlugin("WechatSI")

let manager = plugin.getRecordRecognitionManager()

上面两行代码位置如下图:

image.png

在onload中添加代码:

var that = this;

manager.onRecognize = function (res) {

   cons.log("current result", res.result)

}

manager.onStop = function (res) {

  console.log('识别开始');

  var result = res.result;

  var s = result.indexOf('。') //找到第一次出现下划线的位置

  result = result.substring(0,s)  //取下划线前的字符

  var searchType = that.data.searchType;

  wx.showToast({

    title: result,

  })

}

manager.onError = function (res) {

  console.log('manager.onError')

  console.log(res) //报错信息打印

  wx.showToast({

    title: res.msg,

  })

  // UTIL.log("error msg", res.msg)

}

再继续添加方法:

//手指按下

touchdown_plugin: function () {

var _this = this

// UTIL.stopTTS();

manager.start({

  duration: 30000,

  lang: "zh_CN"

})

},

//手指松开

touchup_plugin: function (e) {

var searchType = e.currentTarget.dataset.type;

this.setData({

  searchType: searchType,

  background:  "#ED6C00",

  yysb:"长按语音识别"

});

manager.stop();

wx.showToast({

  title: '正在识别……',

  icon: 'loading',

  duration: 2000

})

},

最后在xml文件中增加上面两个按下、放开方法绑定即可

image.png

至此同声传译开发完成。希望能够帮助到各位小伙伴,如果有什么不明白,可以下方留言!