微信小程序------音乐播放------背景音乐播放
使用wx.getBackgroundAudioManager()方法播放背景音乐即便突出也会显示音乐播放
1、成品展示
单击右上角按钮播放音乐
2、样式设置
2.1html样式
<view class="player player-{{isPlayingMusic ? 'play' : 'pause'}} " bindtap="play">
<image src="/pages/images/music_icon.png" />
<image src="/pages/images/music_play.png" />
</view>
music_icon.png黑胶唱片,music_play.png长臂照片
2.2css样式
/**index.wxss**/
/* page {
height: 100vh;
display: flex;
flex-direction: column;
} */
/* 音乐图标播放模块 */
.player{
position: fixed;
top:20rpx;
right: 20rpx;
z-index: 1;
}
.player >image:first-child{
width: 80rpx;
height: 80rpx;
animation: musicRotate 3s linear infinite;
}
.player >image:last-child{
width: 28rpx;
height: 80rpx;
margin-left: -2px;
}
@keyframes musicRotate{
from{transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
.player-play>image:first-child{
animation-play-state: running;
}
.player-play>image:last-child{
animation: musicStart 0.2 linear forwards;
}
.player-pause > image:first-child{
animation-play-state: paused;
}
.player-pause>image:last-child{
animation: musicStop 0.2s linear forwards;
}
@keyframes musicStart{
from{transform: rotate(0deg);}
to{transform: rotate(20deg);}
}
@keyframes musicStop{
from{transform: rotate(20deg);}
to{transform: rotate(0deg);}
}
3、效果实现
3.1点击图片旋转
data:{ isPlayingMusic:false, },
play:function(e){
this.setData({
isPlayingMusic:!this.data.isPlayingMusic
})
}
3.2音乐播放
Page({
data:{
isPlayingMusic:false,
},
bgm:null,
music_url:'https://m10.music.126.net/20240526184405/1d9f433e2724be2617af66ca88eb7a82/ymusic/030f/540e/0459/4e5e1c9038cd3bc7cd9133c96db67423.mp3',
music_coverImgUrl:'https://p1.music.126.net/FeMM29SxRV1CcNaaC5_F_A==/109951164042227752.jpg',
onReady:function(){
this.bgm= wx.getBackgroundAudioManager()
this.bgm.title = 'marry me'
this.bgm.epname="wedding"
this.bgm.singer="singer"
this.bgm.coverImgUrl=this.music_coverImgUrl
console.log(this.bgm)
console.log(this.bgm.title)
this.bgm.onCanplay(()=>{
this.bgm.pause()
})
this.bgm.src = this.music_url
},
play:function(e){
if(this.data.isPlayingMusic){
this.bgm.pause()
}else{
this.bgm.play()
}
this.setData({
isPlayingMusic:!this.data.isPlayingMusic
})
}
})