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

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

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)
  }
})

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

以上就是微信小程序实现录音与音频播放功能的详细内容,更多关于小程序录音音频播放的资料请关注www.887551.com其它相关文章!

(0)
上一篇 2022年3月23日
下一篇 2022年3月23日

相关推荐