最近的一个项目中有用到小程序的背景音乐,用法还是挺简单的,在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()
原生小程序中实现的效果: