audio-overlay.js
2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// 音频播放蒙层组件
Component({
properties: {
// 是否显示蒙层
isPlaying: {
type: Boolean,
value: false
},
// 播放的文本内容
audioText: {
type: String,
value: ''
}
},
data: {
progress: 0, // 播放进度百分比
currentTime: '00:00', // 当前播放时间
duration: '00:00', // 总时长
timer: null // 定时器
},
lifetimes: {
detached() {
// 组件销毁时清理定时器
this.clearTimer();
}
},
methods: {
// 初始化音频监听
initAudio(audioContext) {
if (!audioContext) return;
this.audioContext = audioContext;
// 监听音频播放进度
audioContext.onTimeUpdate(() => {
const currentTime = audioContext.currentTime || 0;
const duration = audioContext.duration || 0;
this.setData({
progress: duration > 0 ? (currentTime / duration) * 100 : 0,
currentTime: this.formatTime(currentTime),
duration: this.formatTime(duration)
});
});
// 监听播放结束
audioContext.onEnded(() => {
this.stopPlaying();
});
// 监听播放错误
audioContext.onError(() => {
this.stopPlaying();
});
// 监听播放停止
audioContext.onStop(() => {
this.stopPlaying();
});
},
// 格式化时间显示
formatTime(seconds) {
if (!seconds || isNaN(seconds)) return '00:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
},
// 停止播放
stopPlaying() {
this.setData({
progress: 0,
currentTime: '00:00',
duration: '00:00'
});
this.clearTimer();
// 触发父组件的停止事件
this.triggerEvent('stop');
},
// 清理定时器
clearTimer() {
if (this.data.timer) {
clearInterval(this.data.timer);
this.setData({
timer: null
});
}
},
// 点击蒙层背景
onOverlayTap() {
// 点击背景关闭蒙层并停止播放
this.stopPlaying();
},
// 点击停止按钮
onStopTap() {
this.stopPlaying();
},
// 阻止事件冒泡
stopPropagation() {
// 阻止点击内容区域时触发背景点击事件
}
}
});