欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 小程序语音识别功能 wx.createInnerAudioContext

小程序语音识别功能 wx.createInnerAudioContext

2025/4/1 4:02:02 来源:https://blog.csdn.net/weixin_43612234/article/details/146584827  浏览:    关键词:小程序语音识别功能 wx.createInnerAudioContext

在这里插入图片描述

页面样式html+css
<view class="recorder_content"><view class="result_content"><view class="r_title">语音识别结果显示:</view><view class="r_h_input"><text wx:if="{{resultDetails.result}}" class="{{resultDetails && resultDetails.status <=0 ?'r_h_input_red':''}}">{{ resultDetails.result || '识别失败'}}</text></view></view><view class="button_content"><button bindtouchstart="touchstart" bindtouchend="touchend" disabled="{{!canRecord}}">{{longPress == '1' ? '按住说话' : '说话中...'}}</button><button bindtap="playRecording" disabled="{{!canRecord || !tempFilePath}}">播放录音</button></view>
</view>.recorder_content{width: 100%;display: flex;align-items: center;justify-content: space-between;flex-direction: column;border-top: 1rpx solid #f7f7f7;
}
.result_content{width: 94%;margin: 0 auto;
}.r_title{font-size: 26rpx;padding: 30rpx 0rpx;
}
.r_title_padding-b{padding-bottom: 0rpx;
}
.button_content{width: 100%;display: flex;
}
button{margin: 20rpx auto;font-size: 30rpx;width: 45%;
}.r_h_input_red{color: red;
}
data 初始化数据
data: {canRecord: false,isRecording: false,tempFilePath: '',playbackUrl: '',recorderManager: '',recorderLang: {},longPress: 1, //1显示 按住说话 2显示 说话中,screenHeight: 0,innerAudioContext: null,resultInput: '',resultDetails: {},startTimeStamp: 0},
onLoad和app.js
  onLoad: function () {const innerAudioContext = wx.createInnerAudioContext({useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动,默认关闭。对于短音频、播放频繁的})setTimeout(() => {this.setData({innerAudioContext: innerAudioContext})})this.requestMicrophonePermission();},// app.js 文件内容"scope.record": {"desc": "用于录音"}

在这里插入图片描述

requestMicrophonePermission(获取权限)
requestMicrophonePermission: function () {wx.getSetting({success: (res) => {console.log('获取麦克风权限================', res)console.log(!res.authSetting['scope.record'])if (!res.authSetting['scope.record']) {wx.authorize({scope: 'scope.record',success: (res) => {console.log('用户已授权录音================', res);this.setData({canRecord: true});},fail: (err) => {console.error('用户拒绝授权录音================', err);wx.showModal({title: '需要授权录音',content: '您需要授权录音功能以正常使用本应用',showCancel: false,confirmText: '前往设置',success(res) {if (res.confirm) {wx.openSetting({success(settingRes) {if (settingRes.authSetting['scope.record']) {console.log('用户已授权录音');this.setData({canRecord: true});}}});}}});}});} else {this.setData({canRecord: true});}}});},
长按说话功能
touchstart(e) {console.log('开始---------------------');this.startRecording()},touchend(e) {console.log('结束-------------------');this.setData({longPress: 1,canRecord: true,isRecording: true})if (e.timeStamp - this.data.startTimeStamp < 1000) { //点击wx.showToast({title: '语音时间太短了',icon: 'none',mask: true, // 是否显示透明蒙层,防止触摸穿透duration: 1000})} else { //长按this.stopRecording()}},startRecording() {let that = thisif (that.data.canRecord) {that.setData({isRecording: true,longPress: 2});that.data.recorderManager.start({timeout: 180,format: 'wav', // 音频格式success: (res) => {console.log('wx.startRecord================success', res)},fail: (err) => {console.log('wx.startRecord================fail', err)}});}},
stopRecording() {let that = thisif (that.data.canRecord) {console.log('stop停止事件=>')this.data.recorderManager.onStop((res) => {this.setData({tempFilePath: res.tempFilePath,isRecording: true,canRecord: true,longPress: 1});// 停止录音后,上传文件this.uploadAudio(res.tempFilePath)});// 停止录音this.data.recorderManager.stop()}},
uploadAudio(filePath) {let that = thisif (that.data.canRecord && that.data.tempFilePath) {console.log('wav文件=>', filePath)wx.showToast({title: "加载中",icon: 'loading',mask: true, // 是否显示透明蒙层,防止触摸穿透duration: 100000})wx.uploadFile({url: "服务器上传文件地址",filePath: filePath, // 文件路径name: 'audio', // 服务器接收的文件参数名header: {'Authorization': wx.getStorageSync('token_' + constant.version),'Content-Type': 'multipart/form-data'},formData: {'hotWords': that.data.resultInput,//可以去除,这个字段是后台需要的,根据自己的项目来},success(res) {wx.hideLoading()console.log('上传成功:', JSON.parse(res.data));that.setData({resultDetails: JSON.parse(res.data).data,//后台返回来的数据,用于页面展示})if(JSON.parse(res.data).data.status <=0){that.setData({tempFilePath: '',});}},fail(error) {setTimeout(() => {wx.hideLoading()}, 1000)console.error('上传失败:', error);}})}},
播放录音
playRecording() {let that = thisif (this.data.canRecord && this.data.tempFilePath) {that.data.recorderManager.start()this.data.recorderManager.onStop()that.data.innerAudioContext.src = that.data.tempFilePath;console.log('播放url=>', that.data.innerAudioContext.src)console.log('播放事件=>', that.data.innerAudioContext)that.data.innerAudioContext.play();that.data.innerAudioContext.onPlay(() => {console.log('开始播放');});//return//if (!this.data.innerAudioContext) {//  this.setData({//    innerAudioContext: wx.createInnerAudioContext()//  })//}//this.data.innerAudioContext.src = this.data.tempFilePath;//console.log('播放=>', this.data.innerAudioContext)//this.data.innerAudioContext.play();// this.data.innerAudioContext.onPlay(() => {//   console.log('Playing audio...');// });// this.data.innerAudioContext.onError((err) => {//   console.error('Error playing audio:', err);// });// // 监听音频自然播放至结束的事件,播放结束,停止播放// this.data.innerAudioContext.onEnded(()=>{//   this.data.innerAudioContext.stop();// })}},

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词