一、使用BackgroundAudioManager 播放音频并展示进度
说明:
1.使用图片自带wx.preview 将停止音频播放;(这个是很费解,相当不友好)
2.获取全局唯一的背景音频管理器。 小程序切入后台,如果音频处于播放状态,可以继续播放。但是后台状态不能通过调用API操纵音频的播放状态。
从微信客户端6.7.2版本开始,若需要在小程序切后台后继续播放音频,需要在 app.json 中配置 requiredBackgroundModes 属性。开发版和体验版上可以直接生效,正式版还需通过审核。
wxml
<text>
播放状态:{{audio.currentTime}}s / {{audio.duration}} s
</text>
<slider value="{{audio.percent}}" bindchange="sliderChange"></slider>
<button type="primary" bindtap="payClick">
<text wx:if="{{audio.isPlaying}}">点击暂停</text>
<text wx:else>点击播放</text>
</button>
js:
const context = wx.getBackgroundAudioManager();
Page({
/**
* 页面的初始数据
*/
data: {
audio: {
isPlaying: false, //播放状态
//时间位置
currentTime: 0,
duration: 0,
isWarting: false
},
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var _this = this;
//音频播放处理
//开始播放
context.onPlay(() => {
console.info('开始播放');
});
//进度监听
context.onTimeUpdate(() => {
console.info(context.currentTime, context.duration);
_this.setData({
'audio.currentTime': context.currentTime,
'audio.duration': context.duration,
'audio.percent': context.currentTime / context.duration * 100,
});
});
context.title = '测试音频';
context.epname = '此时此刻'
context.singer = '许巍'
context.coverImgUrl = "http://www.jnqianle.cn/upload/logo/content/202109/24/e2b864e3-5cb7-4785-843a-5e551c59d270.jpg";
context.src = 'http://music.jnqianle.cn/file/audio/9.mp3';
},
//播放暂停
payClick() {
var _this = this;
if (context.paused) {
context.play(); //暂停播放
} else {
context.pause(); //开始播放
}
_this.setData({
'audio.isPlaying': !_this.data.audio.isPlaying
});
},
//切换进度
sliderChange(e) {
var _this = this;
var val = e.detail.value;
var second = context.duration * val / 100;
context.seek(second);
},
})
二、展示效果
更多: