当前位置:Gxlcms > JavaScript > 微信小程序录音与播放录音功能

微信小程序录音与播放录音功能

时间:2021-07-01 10:21:17 帮助过:192人阅读

小程序中提供了两种录音的API

旧版录音功能

首先启动录音,然后停止录音即可拉到音频的临时地址

启动录音:

  1. var that = this;
  2. wx.startRecord({
  3. success: function (res) {
  4. // 调用了停止录音接口就会触发这个函数,res.tempFilePath为录音文件临时路径
  5. var tempFilePath = res.tempFilePath
  6. that.setData({
  7. src: tempFilePath
  8. })
  9. },
  10. fail: function (res) {
  11. //录音失败的处理函数
  12. }
  13. })

停止录音:

  1. wx.stopRecord()

播放录音:

  1. wx.playVoice({
  2. filePath: src // src可以是录音文件临时路径
  3. })

新版录音

获取全局唯一的录音管理器,然后录音都依赖他,而播放录音则需要内部 audio 上下文 innerAudioContext 对象。

获取全局唯一的录音管理器:

  1. var that = this;
  2. this.recorderManager = wx.getRecorderManager();
  3. this.recorderManager.onError(function(){
  4. // 录音失败的回调处理
  5. });
  6. this.recorderManager.onStop(function(res){
  7. // 停止录音之后,把录取到的音频放在res.tempFilePath
  8. that.setData({
  9. src: res.tempFilePath
  10. })
  11. console.log(res.tempFilePath )
  12. });

开始录音:

  1. this.recorderManager.start({
  2. format: 'mp3' // 如果录制acc类型音频则改成aac
  3. });

结束录音:

  1. this.recorderManager.stop()

播放音频:

  1. this.innerAudioContext = wx.createInnerAudioContext();
  2. this.innerAudioContext.onError((res) => {
  3. // 播放音频失败的回调
  4. })
  5. this.innerAudioContext.src = this.data.src; // 这里可以是录音的临时路径
  6. this.innerAudioContext.play()

DEMO地址

github: https://github.com/yubang/appletRecordDemo

总结

以上所述是小编给大家介绍的微信小程序录音与播放录音功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

人气教程排行