Skip to content

Commit 293298b

Browse files
committed
优化缓存方式,防止重复下载.
1 parent 852995a commit 293298b

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

videos/player.js

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const playList = [
1313
];
1414

1515
// 创建播放列表缓存
16-
var blobList = [];
16+
var blobList = {};
1717

1818
/**
1919
* 创建sleep方法(用于async / await的延时处理)
@@ -30,13 +30,14 @@ function sleep(ms) {
3030
async function LoadVideo(linkList) {
3131
for (let i = 0, len = linkList.length; i < len; i++) {
3232
let loadLink = `${playPath}${linkList[i]}`;
33+
//console.log(`[${(new Date()).toTimeString().split(' ')[0]}] onLoad:`, loadLink);
3334
let response = await fetch(loadLink);
3435
if (!response.ok) {
3536
console.log("Failed:", loadLink);
3637
continue;
3738
}
38-
blobList.push(window.URL.createObjectURL(await response.blob()));
39-
console.log("Loaded:", loadLink);
39+
blobList[linkList] = window.URL.createObjectURL(await response.blob());
40+
//console.log(`[${(new Date()).toTimeString().split(' ')[0]}] Loaded:`, loadLink);
4041
}
4142
}
4243

@@ -47,26 +48,26 @@ async function LoadVideo(linkList) {
4748
video.src = URL.createObjectURL(new MediaSource());
4849
// 视频播放结束事件
4950
video.addEventListener('ended', () => {
50-
let index = 0;
51-
let videoLink = video.src;
52-
for (let i = 0, len = blobList.length; i < len; i++) {
53-
if (videoLink == blobList[i]) {
54-
index = ++i < blobList.length ? i : 0;
51+
for (let i = 0, len = playList.length; i < len; ++i) {
52+
if (video.src == blobList[playList[i]]) {
53+
if (++i < len && blobList[playList[i]]) {
54+
video.src = blobList[playList[i]];
55+
if (++i < len && !blobList[playList[i]]) {
56+
LoadVideo([playList[i]]);
57+
}
58+
} else {
59+
video.src = blobList[playList[0]];
60+
}
5561
break;
5662
}
5763
}
58-
video.src = blobList[index];
59-
video.load();
6064
video.play();
61-
// 预加载下一个视频(如果有)
62-
if (++index < playList.length && index >= blobList.length) {
63-
LoadVideo([playList[index]]);
64-
}
6565
});
6666
// 加载播放列表
6767
await LoadVideo([playList[0]]);
6868
// 载入第一个视频
69-
video.src = blobList[0];
69+
video.src = blobList[playList[0]];
70+
video.play();
7071
// 预加载下一个视频
7172
if (playList.length > 1) await LoadVideo([playList[1]]);
7273
})();

0 commit comments

Comments
 (0)