显现的功能
开始播放、暂停播放、停止播放、进度条显示(没有做拖拽进度条)
效果
播放状态是个动图(图是网上随便找的,如侵删,CSDN是我自己的)
暂停状态是静态图片:
app.json设置
首先要在app.json里设置:
"requiredBackgroundModes":["audio","backgroundAudioManager"]
目的是使播放器可以息屏播放。
wxml页面显示设置
<view class="spotAudio">
<image src="https://s4.ax1x.com/2021/12/16/T9w4Zq.gif" wx:if="{{!onplay}}"></image>
<image src="https://s4.ax1x.com/2021/12/16/T9BFhT.png" wx:if="{{onplay}}"></image>
<slider value="{{playTime}}" disabled="true" />
<view class="Mp3Btn">
<button bind:tap="onMusic" wx:if="{{onplay}}">
<van-icon size="22" name="play-circle-o" />
</button>
<button bind:tap="pauseMusic" wx:if="{{!onplay}}">
<van-icon size="22" name="pause-circle-o" />
</button>
<button bind:tap="stopMusic">
<van-icon size="22" name="stop-circle-o" />
</button>
</view>
</view>
图片是用一静一动来表示暂停和播放。
css样式设置
.spotAudio{
margin-left: 8%;
width: 84%;
margin-top: 20px;
margin-bottom: 10px;
}
.spotAudio>image{
height: 150px;
width: 100%;
}
.spotAudio>van-slider{
width: 84%;
}
.Mp3Btn{
display: flex;
justify-content: space-around;
width: 50%;
margin-left: 25%;
margin-top: 15px;
}
.Mp3Btn>button{
margin: 0;
padding: 0;
width: 50px;
}
按钮的样式设置的比较简单,可以自行更改。
js设置
因为我是在接口返回数据中拿到的歌曲数据,所以首先在page上面(全局)设置:
const backgroundAudioManager = wx.getBackgroundAudioManager();
data中用到的数据:
data: {
playTime: \'\',
onplay:false,
},
在接口成功回调函数中设置:
// 音乐播放
backgroundAudioManager.title = \'歌曲标题\';//
backgroundAudioManager.epname = \'专辑名称\';//
backgroundAudioManager.singer = \'歌手\';//
backgroundAudioManager.coverImgUrl = \'https://...(歌曲封面)\';
// 设置了 src 之后会自动播放
backgroundAudioManager.src = \'https://...(歌曲地址)\';
that.setData({
onplay:false
})
let playTime = \'\';
backgroundAudioManager.onPlay(() => {
console.log(\'开始播放\');
let duration = backgroundAudioManager.duration;
let currentTime = backgroundAudioManager.currentTime;
if (currentTime != 0) {
setInterval(() => {
currentTime = backgroundAudioManager.currentTime;
playTime = Number(currentTime / duration) * 100
console.log(currentTime, duration, playTime);
that.setData({
playTime: playTime
})
}, 500)
}
})
backgroundAudioManager.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
播放、暂停、停止的点击事件:
//播放
onMusic() {
backgroundAudioManager.play();
backgroundAudioManager.onPlay(() => {
console.log(\'开始播放\');
})
this.setData({
onplay:false
})
},
//暂停
pauseMusic() {
backgroundAudioManager.pause();
backgroundAudioManager.onPause(() => {
console.log(\'暂停播放\');
})
this.setData({
onplay:true
})
},
//停止
stopMusic() {
backgroundAudioManager.stop();
backgroundAudioManager.onStop(() => {
console.log(\'停止播放\');
})
this.setData({
onplay:true
})
},
请发表评论