当前位置:   article > 正文

微信小程序语音转文字demo_小程序语音转文字api

小程序语音转文字api

最近做了个微信小程序语音输入转文字的需求,记录一下

微信小程序支持通过语音识别 API 实现语音转文字的功能,可以按照以下步骤进行设置:

  1. 在小程序的 json 配置文件中,添加 record 权限:
"permission": {
  "record": {
    "desc": "用于语音输入"
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 在小程序的 wxml 文件中,添加录音组件:
<recorder id="recorder" duration="60000" 
  event-bindend="onRecordEnd" 
  event-binderror="onRecordError"></recorder>
  • 1
  • 2
  • 3

其中,duration 表示录音时长,单位为毫秒。

  1. 在小程序的 js 文件中,使用语音识别 API 将录音转换为文字:
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const options = {
  duration: 60000,
  lang: 'zh_CN'
}

// 语音转文字
const recognize = (tempFilePath) => {
  wx.uploadFile({
    url: 'https://api.weixin.qq.com/cgi-bin/media/voice/addvoicetorecofortext?access_token=' + access_token,
    filePath: tempFilePath,
    name: 'voice',
    success(res) {
      console.log(res.data);
    }
  })
}

// 录音开始
onRecordStart() {
  recorderManager.start(options)
}
// 录音结束
onRecordEnd() {
  recorderManager.stop()
}
// 录音出错
onRecordError(error) {
  console.log('record error:', error);
}
// 录音结束,监听录音结束事件
recorderManager.onStop((res) => {
  console.log('record path:', res.tempFilePath);
  // 播放录音
  innerAudioContext.autoplay = true
  innerAudioContext.src = res.tempFilePath
  // 语音转文字
  recognize(res.tempFilePath)
})
  • 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

以上代码会通过 wx.uploadFile 方法将录音上传到微信的服务器,并使用 API 将录音转换为文字,最终返回转换后的文本结果。在实际开发中,还需要根据实际需求进行代码修改。

注意,使用语音识别 API 需要先获取 access_token,具体参考微信开发者文档。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/797867
推荐阅读
相关标签
  

闽ICP备14008679号