video-compressor/public/assets/scripts/main.js
2025-01-27 21:30:22 +01:00

65 lines
1.8 KiB
JavaScript

async function compress() {
showSection("loading");
const filesize = document.getElementById("filesize").value;
const file = document.getElementById("file-input").files[0];
const ffmpeg = new FFmpegWASM.FFmpeg();
ffmpeg.on("progress", data => {
console.log(data.progress);
});
await ffmpeg.load({ coreURL: "/assets/scripts/core/package/dist/umd/ffmpeg-core.js" });
await ffmpeg.writeFile(file.name, await readFromBlob(file));
await ffmpeg.exec(["-i", file.name, "-fs", filesize + "M", "compressed.mp4"]);
const video = await ffmpeg.readFile("compressed.mp4");
location.href = URL.createObjectURL(new Blob([video.buffer], { type: "video/mp4" }));
}
function selectFile() {
document.getElementById("file-input").click();
}
function showSection(section) {
for (const section of document.getElementsByTagName("section")) {
section.style.opacity = "0";
}
setTimeout(() => {
for (const section of document.getElementsByTagName("section")) {
section.style.display = "none";
}
document.getElementById(section + "-section").style.display = "block";
document.getElementById(section + "-section").style.opacity = "1";
}, 400);
}
// https://github.com/ffmpegwasm/ffmpeg.wasm/blob/main/packages/util/src/index.ts
function readFromBlob(blob) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = () => {
const { result } = fileReader;
if (result instanceof ArrayBuffer) {
resolve(new Uint8Array(result));
} else {
resolve(new Uint8Array());
}
};
fileReader.onerror = (event) => {
reject(
Error(
`File could not be read! Code=${event?.target?.error?.code || -1}`
)
);
};
fileReader.readAsArrayBuffer(blob);
});
}