You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Firebase云函数中获取Storage视频时长的最简方法及报错解决

获取Firebase云函数中视频时长的解决方案

Hey there! Let's figure out how to get the duration of videos uploaded to Firebase Storage using Cloud Functions, and fix that annoying spawn ffprobe ENOENT error you ran into.

先搞懂错误原因

That error happens because the default Node.js environment for Firebase Cloud Functions doesn't come with ffprobe pre-installed. The get-video-duration module relies on ffprobe (part of the ffmpeg suite) to read video metadata, so when it tries to spawn the tool, it can't find it—hence the "ENOENT" (no entry) error.

最简单的解决方法:自动安装ffprobe

The easiest way to fix this is to use @ffmpeg-installer/ffprobe, a package that automatically installs the correct version of ffprobe for your Cloud Functions environment. Here's how to set it up:

Step 1: Install required packages

Run this in your Cloud Functions directory:

npm install get-video-duration @ffmpeg-installer/ffprobe

Step 2: Update your Cloud Function code

Instead of using the public URL of the video (which can have permission issues anyway), use a signed URL to securely access the file from Storage. Then configure get-video-duration to use the installed ffprobe:

const functions = require("firebase-functions");
const { getVideoDurationInSeconds } = require('get-video-duration');
const ffprobe = require('@ffmpeg-installer/ffprobe');
const { Storage } = require('@google-cloud/storage');
const storage = new Storage();

exports.fetchVideoDuration = functions.storage.object().onFinalize(async (object) => {
  // 获取视频的签名URL(无需将文件设为公开)
  const file = storage.bucket(object.bucket).file(object.name);
  const [signedUrl] = await file.getSignedUrl({
    action: 'read',
    expires: '2030-01-01' // 设置一个合理的过期时间
  });

  try {
    // 使用安装好的ffprobe获取视频时长
    const durationInSeconds = await getVideoDurationInSeconds(signedUrl, {
      ffprobePath: ffprobe.path
    });

    console.log(`视频时长:${durationInSeconds}秒(或${Math.floor(durationInSeconds/60)}分${Math.floor(durationInSeconds%60)}秒)`);
    
    // 在这里可以把时长存入Firestore或其他位置
    // const firestore = admin.firestore();
    // await firestore.collection('videos').doc(object.name).set({ duration: durationInSeconds });
  } catch (error) {
    console.error('获取视频时长出错:', error);
    throw error;
  }
});

为什么用签名URL而不是公开URL?

  • 安全性:你不需要把视频文件设为公开可访问,签名URL只提供临时的、受限的访问权限。
  • 可靠性:公开URL在云函数中访问时可能遇到CORS或权限问题,而签名URL在Google云生态系统内可以无缝工作。

额外注意事项

  • 内存配置:解析视频文件比较消耗资源,建议在Firebase控制台中将函数的内存分配设置为至少512MB(大视频建议1GB)。
  • 超时设置:如果处理大视频,需要调高函数的超时限制(云函数最长支持9分钟)。

内容的提问来源于stack exchange,提问作者Osama Alsalman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:18:23