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

Ffmpeg输出文件打开失败求助:Next.js项目嵌入字幕报错

问题分析与解决方案

核心问题

你遇到的Error opening output file本质是路径解析错误和目录不存在导致的:

  1. 代码中使用的相对路径(./output_withsrt.mp4)在Next.js运行时的工作目录下不存在,VS Code启动服务时的工作目录可能和手动执行命令行时不一致。
  2. SRT文件路径用了Next.js的别名@/,fluent-ffmpeg无法识别该别名,导致找不到字幕文件(间接引发输出文件写入失败)。
  3. 如果输出路径对应的目录不存在,ffmpeg不会自动创建目录,直接报错。

具体修复步骤

1. 补全依赖模块导入

在代码开头导入path和fs模块(你之前用了path.join但未导入):

import ffmpeg from "fluent-ffmpeg";
import { NextRequest } from "next/server";
import path from "path";
import fs from "fs";

ffmpeg.setFfmpegPath('C:\\ffmpeg\\bin\\ffmpeg.exe')

2. 替换所有相对路径为绝对路径

  • 处理SRT文件路径:把Next.js别名@/转换成项目根目录的绝对路径
  • 处理输出文件路径:用path.join拼接绝对路径,提前确保目录存在

修改embedSubtitle函数:

async function embedSubtitle(videopath: string, srtFilePath: string, outputPath: string): Promise<boolean>{
  if(!videopath || !srtFilePath || !outputPath) return false

  // 转换SRT路径:替换@/为项目根目录下的路径
  const resolvedSrtPath = srtFilePath.replace('@/', `${process.cwd()}/`);
  // 确保输出目录存在,不存在则递归创建
  const outputDir = path.dirname(outputPath);
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  try {
    await new Promise<void>((resolve, reject) => {
      ffmpeg()
      .input(videopath)
      .videoFilters(`subtitles=${resolvedSrtPath}:force_style='Fontsize=24'`)
      .output(outputPath) // 直接使用传入的绝对路径
      .on("end", () => {
        console.log("Subtitle added successfully");
        resolve()
      })
      .on("error", (err, stderr) => {
        console.error("Error during conversion and subtitle adding", err)
        console.error("stderr", stderr)
        reject(err);
      })
      .run()
    })
    return true
  } catch (error) {
    console.log("error while embedding subtitle in a video")
    return false;
  }
}

3. 调用时传入正确的绝对路径

修改POST函数中的调用参数,用绝对路径替换相对路径:

export async function POST(req: NextRequest) {
  try {
    const srtPath = path.join(process.cwd(), "public", "srtfile", "output.srt");
    const outputPath = path.join(process.cwd(), "public", "srtfile", "giveme.mp4");

    console.log("yaha tak");

    await embedSubtitle(
      "http://res.cloudinary.com/dptgkunzk/video/upload/v1717785028/w8ezkazwhsqbyx7f34rw.mp4",
      srtPath,
      outputPath
    );

    console.log("calling")
  } catch (error) {
    console.log("Something went wrong while adding subtitle");
  }

  return Response.json({ message: "done" });
}

额外注意事项

  • Windows路径转义:你已正确设置ffmpeg路径的转义(C:\\ffmpeg\\bin\\ffmpeg.exe),保持即可。
  • Next.js权限问题:开发环境下写入public目录没问题,但生产环境建议不要写入public,可改用临时目录或云存储。
  • 命令行测试对比:手动执行ffmpeg时,确保工作目录是项目根目录,这样才能和代码中的process.cwd()保持一致。

内容的提问来源于stack exchange,提问作者Priyanshu Tiwari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:12:10