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

页面样式html+css
javascript 复制代码
<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 初始化数据
javascript 复制代码
data: {
    canRecord: false,
    isRecording: false,
    tempFilePath: '',
    playbackUrl: '',
    recorderManager: '',
    recorderLang: {},
    longPress: 1, //1显示 按住说话 2显示 说话中,
    screenHeight: 0,
    innerAudioContext: null,
    resultInput: '',
    resultDetails: {},
    startTimeStamp: 0
  },
onLoad和app.js
javascript 复制代码
  onLoad: function () {
    const innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动,默认关闭。对于短音频、播放频繁的
    })
    setTimeout(() => {
      this.setData({
        innerAudioContext: innerAudioContext
      })
    })

    this.requestMicrophonePermission();
  },

	// app.js 文件内容
	"scope.record": {
      "desc": "用于录音"
    }
requestMicrophonePermission(获取权限)
javascript 复制代码
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
          });
        }
      }
    });
  },
长按说话功能
javascript 复制代码
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);
        }
      })
    }
  },
播放录音
javascript 复制代码
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();
      // })

    }
  },
相关推荐
时代文章几秒前
AI 基础知识体系
人工智能·ai
开开心心_Every1 分钟前
界面干净的开源免费电视浏览器
人工智能·科技·智能手机·计算机外设·rabbitmq·语音识别·etcd
Hooray5 分钟前
告别低效循环!AI Agent 编排+编程显示器,让前端开发效率实现断代式跃升
前端·人工智能·ai编程
菜鸟‍5 分钟前
【论文学习】2026.5 || 分解式视觉-语言对齐用于细粒度开放词汇分割
人工智能·深度学习·计算机视觉
大山佬6 分钟前
硬件原理图与 PCB 实战:从信号完整性到 EMC 合规
人工智能
AI科技星8 分钟前
第六卷:量天尺传奇(几何学)
网络·人工智能·算法·概率论·学习方法·几何学·拓扑学
莱歌数字9 分钟前
FloEFD网格文件:核心概念、分类方法与工程实战指南
人工智能·科技·制造·散热·液冷散热
txg66621 分钟前
机器人领域简报(2026年6月7日—14日)
大数据·人工智能·机器人
4A广告文案25 分钟前
品牌负面评论难排查?AI情绪分析实时抓取全网评论,提前规避公关翻车
人工智能
Z-D-K27 分钟前
S-44的周末”旅行“-周日
人工智能·ai·aigc·交互·agi