如何在 Node.js 中从 Zip 文档获取视频总长度
介绍
在本教程中,我们将深入研究使用 Node.js 计算 zip 存档中包含的视频总时长的过程。这对于媒体管理、视频编辑或任何需要快速评估压缩文件中总视频片段的场景特别有用。
先决条件:
**安装:**
您的系统上安装了 Node.js 和 npm(或 yarn)。
**创建一个新的 Node.js 项目:**
`mkdir 视频持续时间计算器
cd 视频时长计算器
npm init -y`
**安装所需的依赖项:**
`npm install unzipper get-video-duration path fs
`
**代码实现index.ts:**
import * as fs from "fs";
import { getVideoDurationInSeconds } from "get-video-duration";
import * as unzipper from "unzipper";
import * as path from "path";
async function calculateTotalDuration(zipFilePath: string): Promise {
try {
let totalDurationSeconds = 0;
const directory = await unzipper.Open.file(zipFilePath);
for (const entry of directory.files) {
if (entry.path.match(/\.(mp4|mov|avi|mkv)$/i)) {
const videoData = await entry.buffer();
// Construct the temporary file path (cross-platform compatible)
const tempFilePath = `./temp_${entry.path.replace(/[/\\]/g, "_")}`;
console.log("Entry name:", entry.path);
console.log("Temporary file path:", tempFilePath);
// Ensure the directory exists (cross-platform compatible)
const dirName = tempFilePath.substring(
0,
tempFilePath.lastIndexOf(path.sep)
);
if (!fs.existsSync(dirName)) {
fs.mkdirSync(dirName, { recursive: true });
}
fs.writeFileSync(tempFilePath, videoData);
try {
await new Promise((resolve) => setTimeout(resolve, 100));
const duration = await getVideoDurationInSeconds(tempFilePath);
totalDurationSeconds += duration;
} catch (readError) {
console.error(
`Error reading video duration from ${tempFilePath}:`,
readError
);
} finally {
try {
fs.unlinkSync(tempFilePath);
} catch (deleteError) {
console.error(
`Error deleting temporary file ${tempFilePath}:`,
deleteError
);
}
}
}
}
const totalDurationMinutes = totalDurationSeconds / 60;
return parseFloat(totalDurationMinutes.toFixed(2));
} catch (error) {
console.error("Error calculating total duration:", error);
throw error;
}
}
// Example usage (adjust the path according to your OS)
const zipFilePath =
process.platform === "win32"
? "C:\\Users\\your-username\\Downloads\\video-test-duretion.zip"
: "/home/lcom/Documents/video-test-duretion.zip";
calculateTotalDuration(zipFilePath)
.then((totalDurationMinutes) => {
console.log(`Total duration of videos =>: ${totalDurationMinutes} minutes`);
})
.catch((error) => {
console.error("Error:", error);
}); **解释:**
**请记住:**