温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

微信小程序如何实现录音与音频播放功能

发布时间:2022-03-21 11:23:18 来源:亿速云 阅读:2337 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关微信小程序如何实现录音与音频播放功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

小程序继承了微信强大的语音处理功能,提供了录音、音频播放控制和背景音乐等功能,它们的功能不同,但有相似性。

1、录音

小程序提供了wx.startRecord(Object object)开始录音、wx.stopRecord()停止录音和RecorderManager录音管理器等接口对录音功能进行控制。因为RecorderManager录音管理器包含前两个接口的功能,所以这里只介绍RecorderManager。

接口功能和用途
RecorderManager.resume()继续录音
RecorderManager.stop()停止录音
RecorderManager.onStart(function callback)监听录音开始事件
RecorderManager.onResume(function callback)监听录音继续事件
RecorderManager.onPause(function callback)监听录音暂停事件
RecorderManager.onStop(function callback)监听录音结束事件
RecorderManager.onFrameRecorded(function callback)监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
RecorderManager.onError(function callback)监听录音错误事件

在使用录音接口时,需要先授权开放录音功能。

1.1 案例

本例使用RecorderManager录音管理器实现录音、暂停、继续录音、停止录音和播放录音等功能。

redorderManager.wxml

<button bindtap="start" class='btn'>开始录音</button>
<button bindtap="pause" class='btn'>暂停录音</button>
<button bindtap="resume" class='btn'>继续录音</button>
<button bindtap="stop" class='btn'>停止录音</button>
<button bindtap="play" class='btn'>播放录音</button>

redorderManager.js

const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()

Page({
  data: {
  },
  onLoad: function () {
  
  },
  //开始录音的时候
  start: function () {
    var that=this
    const options = {
      duration: 10000,//指定录音的时长,单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式,有效值 aac/mp3
      frameSize: 50,//指定帧大小,单位 KB
    }
    //开始录音
    wx.authorize({
      scope: 'scope.record',
      success() {
        console.log("录音授权成功");
        //第一次成功授权后 状态切换为2
        that.setData({
          status: 2,
        })
        recorderManager.start(options);
        recorderManager.onStart(() => {
          console.log('recorder start')
        });
        //错误回调
        recorderManager.onError((res) => {
          console.log(res);
        })
      },
      fail() {
        console.log("第一次录音授权失败");
        wx.showModal({
          title: '提示',
          content: '您未授权录音,功能将无法使用',
          showCancel: true,
          confirmText: "授权",
          confirmColor: "#52a2d8",
          success: function (res) {
            if (res.confirm) {
              //确认则打开设置页面(重点)
              wx.openSetting({
                success: (res) => {
                  console.log(res.authSetting);
                  if (!res.authSetting['scope.record']) {
                    //未设置录音授权
                    console.log("未设置录音授权");
                    wx.showModal({
                      title: '提示',
                      content: '您未授权录音,功能将无法使用',
                      showCancel: false,
                      success: function (res) {

                      },
                    })
                  } else {
                    //第二次才成功授权
                    console.log("设置录音授权成功");
                    that.setData({
                      status: 2,
                    })
             
                    recorderManager.start(options);
                    recorderManager.onStart(() => {
                      console.log('recorder start')
                    });
                    //错误回调
                    recorderManager.onError((res) => {
                      console.log(res);
                    })
                  }
                },
                fail: function () {
                  console.log("授权设置录音失败");
                }
              })
            } else if (res.cancel) {
              console.log("cancel");
            }
          },
          fail: function () {
            console.log("openfail");
          }
        })
      }
    })
   
   
  },
  //暂停录音
  pause: function () {
    recorderManager.pause();
    recorderManager.onPause((res) => {

      console.log('暂停录音')

    })
  },
  //继续录音
  resume: function () {
    recorderManager.resume();
    recorderManager.onStart(() => {
      console.log('重新开始录音')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },
  //停止录音
  stop: function () {
    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath)
      const { tempFilePath } = res
    })
  },
  //播放声音
  play: function () {
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
  
})

通过recorderManager.wxml中的5个按钮来调用RecorderManager录音管理器的录音、暂停、继续录音、停止录音和播放录音功能。在录制好音频之后也可以上传到服务器,本例只是把录制好的音频存放在手机临时目录,然后用来播放。

微信小程序如何实现录音与音频播放功能

这个功能不好再文章中展示,暂时不加视频了,直到原理就行。

2、音频播放控制

wx.createAudioContext()接口和wx.createInnerAudioContext接口包含了大多数音频控制功能。这里主要介绍wx.createAudioContext()接口。wx.createAudioContext()是以组件<audio>为基础的操作。

AudioContext实例对象可通过wx.createAudioContext接口获取,它通过id跟一个<audio>组件绑定,操作对应的<audio>组件。AudioContext对象常用的函数如下所示。

接口功能和用途
AudioContext.setSrc(string src)设置音频地址
AudioContext.play()播放音频。
AudioContext.pause()暂停音频。
AudioContext.seek(number position)跳转到指定位置(单位,s)。

2.1 案例

本例通过wx.createAudioContext()接口湖区AudioContext实例,然后调用播放和暂停功能,最后用slider组件来定位播放位置。

AudioContext.wxml:

<audio poster="{{poster}}" name="{{name}}" author="{{author}}" src="{{src}}" id="myAudio" controls loop></audio>
<slider bindchange='change' min="0" max="160" value="{{time}}" color="blue" selected-color="red" show-value="true"></slider>
<button class='b1' type="primary" size="mini" bindtap="audioPlay">播放</button>
<button class='b1' type="primary" size="mini"  bindtap="audioPause">暂停</button>

AudioContext.js:

Page({
  onReady: function (e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    this.audioCtx = wx.createAudioContext('myAudio')
  },
  data: {
    time:0,
    poster: 'https://y.qq.com/music/photo_new/T002R300x300M000002Neh8l0uciQZ_1.jpg?max_age=2592000',
    name: '稻香',
    author: '周杰伦',
    src: 'https://dl.stream.qqmusic.qq.com/RS020643ANK71H36gh.mp3?guid=5172738896&vkey=0B819C7570AAF78CC43A7C651E2C8C33FC76A07422EA718B9F8CAFD013F1BCF9E2DAF271064E05939716E400CE460A04669DFAC314460BB9&uin=1144722582&fromtag=66',
  },
  audioPlay: function () {
    this.audioCtx.play()
  },
  audioPause: function () {
    this.audioCtx.pause()
  },
  audio14: function () {
    this.audioCtx.seek(0)
  },

  change: function (e) {
    console.log(e)
    this.audioCtx.seek(e.detail.value)
  }
})

微信小程序如何实现录音与音频播放功能

点击播放之后,就有一首免费的稻香了。

关于“微信小程序如何实现录音与音频播放功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI