赞
踩
最近做了个微信小程序语音输入转文字的需求,记录一下
微信小程序支持通过语音识别 API 实现语音转文字的功能,可以按照以下步骤进行设置:
json
配置文件中,添加 record
权限:"permission": {
"record": {
"desc": "用于语音输入"
}
}
wxml
文件中,添加录音组件:<recorder id="recorder" duration="60000"
event-bindend="onRecordEnd"
event-binderror="onRecordError"></recorder>
其中,duration
表示录音时长,单位为毫秒。
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) })
以上代码会通过 wx.uploadFile
方法将录音上传到微信的服务器,并使用 API
将录音转换为文字,最终返回转换后的文本结果。在实际开发中,还需要根据实际需求进行代码修改。
注意,使用语音识别 API 需要先获取 access_token,具体参考微信开发者文档。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。