小程序 - 背景音乐效果

最近的一个项目中有用到小程序的背景音乐,用法还是挺简单的,在wepy中写了一次,又在原生小程序中练了一次,现记录下来;

<view class="g-container">
  <view class="m-img-banner">
    <image mode="widthFix" src="/image/banner.png" class="img"></image>
  </view>
  <view class="m-activity-top">
  	//音乐图标 用 animation-play-state 控制暂停与播放
    <view class="activity-img" @tap="onmusicTap" style="animation-play-state: {{isplay ? 'running' : 'paused'}}">
      <image mode="widthFix" src="/image/music.png" class="img"></image>
    </view>
  </view>
</view>
//全局声明backgroundAudioManager
let backgroundAudioManager;
export default class Index extends wepy.page {
  config = {
    navigationBarTitleText: '玛丽艳彩妆达人秀总决赛',
  }
  data = {
    //默认值
    isplay: true
  }
  async onLoad(option = {}) {
    backgroundAudioManager =  wx.getBackgroundAudioManager()
    backgroundAudioManager.title = '背景音乐'
    // 设置了 src 之后会自动播放
    backgroundAudioManager.src =  'https://vote.xshuli.com/assets/music.mp3'
    //用于循环播放音乐
    backgroundAudioManager.onEnded(function() {
       backgroundAudioManager.src =  'https://vote.xshuli.com/assets/music.mp3'
    })
  }
  methods = {
    // 点击图标执行 false/暂停  true/播放
    onmusicTap = {
      var that = this 
      //  判断点击时当前isplay的状态
      if (that.isplay) {
         that.isplay = false
         backgroundAudioManager.pause()
      } else {
          that.isplay = true
          backgroundAudioManager.play()
      }
    }
  }
}
1、音乐在静音模式下也会播放;
2、that.isplay指的是在data中的isplay的值;
3、同理,我们可以利用true 和 false 的两种不同的状态在其触发点击效果时 添加不同的类(calss)元素,以达到我们想要的效果;如: class="{{isplay ? ‘show’ : ‘hide’}}"
4、animation-play-state - 属性规定动画正在运行还是暂停,通过搭配三元运算符来控制音乐图标的暂停和运行的动画效果;参考地址:MDN- animation-play-state

文档地址:wx.BackgroundAudioManager()


原生小程序中实现的效果:
在这里插入图片描述

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值