小程序语音识别功能 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();
      // })

    }
  },
相关推荐
救救孩子把3 分钟前
NLU 语义解析评测实践:基于函数调用的 ACC、ROUGE 与 BLEU 综合指标
人工智能·evaluate·nlu·acc
三道杠卷胡4 分钟前
【AI News | 20250729】每日AI进展
人工智能·python·计算机视觉·语言模型·aigc
zzywxc78740 分钟前
随着人工智能技术的飞速发展,大语言模型(Large Language Models, LLMs)已经成为当前AI领域最引人注目的技术突破。
人工智能·深度学习·算法·低代码·机器学习·自动化·排序算法
AI扶我青云志1 小时前
BERT 的 NSP慢慢转换为SOP
人工智能·自然语言处理·llm
博闻录1 小时前
观远 ChatBI 完成 DeepSeek-R1 大模型适配:开启智能数据分析跃升新篇
大数据·人工智能·数据分析
掘金一周1 小时前
一文带你上手 AI Agent 编程 | 掘金一周 7.31
前端·人工智能·后端
掘金安东尼1 小时前
AI 的十年周期规律:从专家系统到大模型,下一步是什么?
人工智能
SEO_juper1 小时前
从人工到智能:SEO测试工作流的AI集成框架与ROI提升方案
人工智能·ai·chatgpt·工具·seo·数字营销
网安INF1 小时前
【论文阅读】-《RayS: A Ray Searching Method for Hard-label Adversarial Attack》
论文阅读·人工智能·深度学习·计算机视觉·网络安全·对抗攻击
walnut_oyb1 小时前
论文阅读|CVPR 2025|Mamba进一步研究|GroupMamba
论文阅读·人工智能·神经网络·计算机视觉·分类