-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
86 lines (82 loc) · 2.25 KB
/
index.ts
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
function getTypeFromBinaryData(binaryData: Uint8Array) {
if (
binaryData[4] === 0x66 &&
binaryData[5] === 0x74 &&
binaryData[6] === 0x79 &&
binaryData[7] === 0x70
) {
return "mp4";
} else if (
binaryData[0] === 0x46 &&
binaryData[1] === 0x4c &&
binaryData[2] === 0x56
) {
return "flv";
} else if (
binaryData[0] === 0x23 &&
binaryData[1] === 0x48 &&
binaryData[2] === 0x54 &&
binaryData[3] === 0x54
) {
return "m3u8";
} else if (
binaryData[0] === 0x44 &&
binaryData[1] === 0x44 &&
binaryData[2] === 0x53 &&
binaryData[3] === 0x4d
) {
return "dash";
}
}
async function getVideoType(
video: string | File
): Promise<"mp4" | "flv" | "m3u8" | "dash" | undefined> {
if (typeof video === "string") {
return fetch(video)
.then(async (res) => {
const arrayBuffer = await res.arrayBuffer();
const binaryData = new Uint8Array(arrayBuffer);
return getTypeFromBinaryData(binaryData);
})
.catch(() => {
return undefined;
});
} else {
const arrayBuffer = await video.arrayBuffer();
const binaryData = new Uint8Array(arrayBuffer);
return getTypeFromBinaryData(binaryData);
}
}
async function getVideoDuration(video: string | File): Promise<number> {
const el = document.createElement("video");
el.src = typeof video === "string" ? video : URL.createObjectURL(video);
return new Promise((resolve, reject) => {
el.addEventListener("loadedmetadata", () => {
if (el.duration === Infinity) {
el.currentTime = Number.MAX_SAFE_INTEGER;
el.ontimeupdate = () => {
el.ontimeupdate = null;
resolve(el.duration);
el.currentTime = 0;
};
} else resolve(el.duration);
});
el.onerror = (event) => {
reject(event);
};
});
}
async function getVideoSize(video: string | File): Promise<number> {
if (typeof video === "string") {
return fetch(video, { method: "HEAD" }).then((res) => {
return parseInt(res.headers.get("Content-Length") || "0");
});
} else {
return video.size;
}
}
export default {
getVideoType,
getVideoDuration,
getVideoSize,
};