美文网首页
微信小程序同时播放两个/多个背景音乐及音效

微信小程序同时播放两个/多个背景音乐及音效

作者: Nosaj | 来源:发表于2019-06-22 17:26 被阅读0次

最近写一个个人小程序 想给里面加点音效 遇到了不能同时播放两个音效的问题 搜到了一些资料整理了一下
原理就是创建5个innerAudioContext实例化对象,轮流调用。(小程序只能同时存在5个音频实例)。
附上demo:

const innerAudioContext1 = wx.createInnerAudioContext(),
  innerAudioContext2 = wx.createInnerAudioContext(),
  innerAudioContext3 = wx.createInnerAudioContext(),
  innerAudioContext4 = wx.createInnerAudioContext(),
  innerAudioContext5 = wx.createInnerAudioContext();

Page({
  tap() {    // 此函数点击调用
    this.vioce();
  },
  vioce() {
    const inner = [innerAudioContext1, innerAudioContext2, innerAudioContext3, innerAudioContext4, innerAudioContext5];
    let filePath = "音频地址";
    let index = app.globalData.index;
    index++;
    if (index > 4) {
      index = 0
    }
    app.globalData.index = index
    inner[index].src = filePath;  
    inner[index].stop()
    inner[index].play()

  }
})

这个API已经没人维护 现在用最新的 BackgroundAudioManager
示例DEMO

const bgMusic = wx.getBackgroundAudioManager()  //创建背景音乐
Page({
 
  data: {
    id: '',//请求数据参数id
    picMsg: {},//接收数据对象
  },
 
  onLoad: function (options) {
    var that = this
    that.setData({
      id: options.id,
    })
    that.getPicInfo() //请求服务器
  }, 
  // 开始播放
  listenerButtonPlay: function (src) {
    var that = this
    console.log(src)
    bgMusic.src = src;
    bgMusic.onTimeUpdate(() => {  //监听音频播放进度
      console.log(bgMusic.currentTime)
    })
    bgMusic.onEnded(() => {  //监听音乐自然播放结束
      console.log("音乐播放结束");
      that.listenerButtonPlay(that.data.picMsg.mp3)
    })
    bgMusic.play(); //播放音乐
  },
  getPicInfo() {
    var that = this
    wx.request({
      url: 'https://xxxxx.xxxxx.com/1.json?id=' + that.data.id,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      success: function (res) {
        that.listenerButtonPlay(res.data.data.mp3) //成功回调执行播放音乐
        that.setData({
          picMsg: res.data.data, //赋值对象
        })
 
      }
    })
  },
 
  onUnload() {
    var that = this
    that.listenerButtonStop()//页面卸载时停止播放
    console.log("离开")
  },
 
  //暂停
  audioPause: function () {
    var that = this
    bgMusic.pause(); //暂停播放音乐
    console.log('暂停')
  },
  audioPlay: function () {
    var that = this
    bgMusic.play(); //停止播放
    console.log('继续播放')
  },
  //停止播放
  listenerButtonStop: function () {
    bgMusic.stop()
  },
})

相关文章

网友评论

      本文标题:微信小程序同时播放两个/多个背景音乐及音效

      本文链接:https://www.haomeiwen.com/subject/smevqctx.html