如何在 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);
  });

**解释:**

  • 解压:代码使用解压库从 zip 档案中提取视频文件。
  • 创建临时文件:每个提取的视频都保存到一个临时文件中。
  • 视频时长计算:get-video-duration 库用于计算每个临时视频文件的时长。
  • 总时长计算:所有视频的总时长通过将所有视频时长相加来计算。
  • 清理:处理后删除临时文件。
  • 跨平台兼容性:
  • 该代码设计为通过使用 path.sep 属性来确定正确的文件分隔符,从而可以在 Windows 和 Linux 系统上运行。
  • **请记住:**

  • 将占位符 zipFilePath 替换为您的 zip 文件的实际路径。
  • 使用 npm install 安装所需的依赖项(unzipper 和 get-video-duration)。
  • 根据您的具体用例的需要调整代码和错误处理。
  • 通过遵循这些步骤并理解代码的逻辑,您可以使用 Node.js 有效地从 zip 存档中计算出视频的总时长。