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

发布于:2025-03-29 ⋅ 阅读:(28) ⋅ 点赞:(0)

在这里插入图片描述

页面样式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 = this
    if (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 = this
    if (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 = this
    if (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 = this
    if (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();
      // })

    }
  },