Page({
data: {
// 播放状态
isPlaying: false,
// 当前播放时间(秒)
currentTime: 0,
// 音频总时长(秒)
duration: 0,
// 进度条百分比
progress: 0,
// 测试用的网络音频地址(公开可访问)
audioUrl: 'https://www.cambridgeenglish.org/images/153149-movers-sample-listening-test-vol2.mp3'
},
// 音频实例(全局唯一,避免重复创建)
audioContext: null,
onLoad(options) {
// 初始化音频实例
this.initAudioContext();
},
/**
* 初始化音频实例,绑定监听事件
*/
initAudioContext() {
// 创建音频实例
this.audioContext = wx.createInnerAudioContext();
// 设置音频地址
this.audioContext.src = encodeURI(this.data.audioUrl);
// ========== 绑定音频事件 ==========
// 播放开始事件
this.audioContext.onPlay(() => {
const vs = wx.getSystemInfoSync().SDKVersion
console.log(vs);
console.log('音频开始播放');
this.setData({
isPlaying: true
});
});
// 暂停事件
this.audioContext.onPause(() => {
console.log('音频暂停播放');
this.setData({
isPlaying: false
});
});
// 停止事件
this.audioContext.onStop(() => {
console.log('音频停止播放');
this.setData({
isPlaying: false,
currentTime: 0,
progress: 0
});
});
// 播放结束事件
this.audioContext.onEnded(() => {
console.log('音频播放结束');
this.setData({
isPlaying: false,
currentTime: 0,
progress: 0
});
// 播放结束后回到起点
this.audioContext.seek(0);
});
// 音频时长加载完成事件(必须等这个事件,才能拿到总时长)
this.audioContext.onCanplay(() => {
// 延迟获取时长(避免时长未加载完成)
setTimeout(() => {
const duration = this.audioContext.duration;
this.setData({
duration
});
console.log('音频时长加载完成:', duration, '秒');
}, 500);
});
// 播放进度更新事件(每秒触发多次)
this.audioContext.onTimeUpdate(() => {
const currentTime = this.audioContext.currentTime;
const duration = this.audioContext.duration;
// 计算进度百分比(用于滑块显示)
const progress = duration > 0 ? (currentTime / duration) * duration : 0;
this.setData({
currentTime,
progress
});
});
// 播放错误事件(关键:排查播放失败原因)
this.audioContext.onError((error) => {
console.error('音频播放错误:', error);
wx.showToast({
title: `播放失败:${error.errMsg}`,
icon: 'none',
duration: 3000
});
this.setData({
isPlaying: false
});
});
},
/**
* 播放/暂停切换
*/
togglePlay() {
if (this.data.isPlaying) {
this.audioContext.pause();
} else {
setTimeout(() => {
this.audioContext.play();
}, 500)
}
},
/**
* 停止播放(回到起点)
*/
stopPlay() {
this.audioContext.stop();
},
/**
* 拖动进度条调整播放位置
*/
seekAudio(e) {
const seekTime = e.detail.value;
this.audioContext.seek(seekTime);
this.setData({
currentTime: seekTime,
progress: seekTime
});
},
/**
* 格式化时间(秒 → 分:秒,如 65 → 1:05)
*/
formatTime(seconds) {
if (!seconds || seconds < 0) return '00:00';
// 取分钟
const min = Math.floor(seconds / 60);
// 取秒
const sec = Math.floor(seconds % 60);
// 补零(如 1 → 01)
return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
},
/**
* 页面卸载时销毁音频实例(避免内存泄漏)
*/
onUnload() {
if (this.audioContext) {
this.audioContext.destroy();
console.log('音频实例已销毁');
}
}
});
