next.js 如何修复'ffmpeg.load()failed to fetch' TypeError?

l2osamch  于 2023-03-29  发布在  其他
关注(0)|答案(1)|浏览(369)

我试图创建一个函数,使用ffmpeg在Next.js中为视频添加文本水印,我一直遇到同样的错误,我不知道如何修复它。
类型错误:无法获取
int getchar();
代码中没有错误,错误只发生在我点击添加水印按钮后的浏览器中。
服务器组件:app/api/addwatermark.ts

import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';

const ffmpeg = createFFmpeg({ log: true });

export default async function addWatermark(
  inputFile: File,
  text: string
): Promise<string> {
  if (!ffmpeg.isLoaded()) {
    await ffmpeg.load();
    // Error ☝️
  }

  ffmpeg.FS('writeFile', inputFile.name, await fetchFile(inputFile));

  await ffmpeg.run(
    '-i',
    inputFile.name,
    '-filter_complex',
    `drawtext=text='${text}':fontfile=Arial.ttf:fontcolor=white@0.8:fontsize=40:x=(w-text_w)/2:y=(h-text_h)/2`,
    'output.mp4'
  );

  const data = ffmpeg.FS('readFile', 'output.mp4');

  const videoUrl = URL.createObjectURL(
    new Blob([data.buffer], { type: 'video/mp4' })
  );

  return videoUrl;
}

客户端组件网:

export default function VideoWatermark() {
  const [inputFile, setInputFile] = useState<File>();
  const [outputFile, setOutputFile] = useState<string>();
  const [text, setText] = useState<string>('');

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      setInputFile(event.target.files[0]);
      setOutputFile(undefined);
    }
  };

  const handleWatermark = async () => {
    if (!inputFile) {
      return;
    }
    const output = await addWatermark(inputFile, text);
    setOutputFile(output);
  };

  return (
    <div>
      <input type='file' onChange={handleFileChange} />
      <br />
      <input
        value={text}
        type='text'
        onChange={(event) => setText(event.target.value)}
      />
      <br />
      <button onClick={handleWatermark}>Add Watermark</button>
      {outputFile && (
        <div>
          <video controls>
            <source src={outputFile} type='video/mp4' />
          </video>
        </div>
      )}
    </div>
  );
}
jtoj6r0c

jtoj6r0c1#

https://github.com/ffmpegwasm/ffmpeg.wasm
为什么它在我的本地环境中不起作用?
当调用ffmpeg.load()时,默认情况下它会查找http://localhost:3000/node_modules/@ ffmpeg/core/dist/来下载必要的文件(ffmpeg-core.js,ffmpeg-core.wasm,ffmpeg-core.worker.js)。有必要确保您在那里提供了这些文件。
如果这些文件位于其他位置,可以重写调用createFFmpeg()时的默认行为:

const { createFFmpeg } = FFmpeg;
const ffmpeg = createFFmpeg({
  corePath: "http://localhost:3000/public/ffmpeg-core.js",
  // Use public address if you don't want to host your own.
  // corePath: 'https://unpkg.com/@ffmpeg/core@0.10.0/dist/ffmpeg-core.js'
  log: true,
});

我将ffmpeg-core.jsffmpeg-core.wasmffmpeg-core.worker.js文件移动到公用文件夹。
我就像下面这样使用它。

const ffmpeg = createFFmpeg({ log: true, corePath: `http://localhost:3000/ffmpeg/ffmpeg-core.js` });

如果您使用的是NextJS,请将核心文件复制到NextJS项目中的/public
例如,将核心文件复制到/public/ffmpeg,并在浏览器中使用以下URL进行测试。
http://localhost:3000/ffmpeg/ffmpeg-core.js
访问此URL并验证文件的内容是否已显示。
最后,将corePath设置为上面的URL并重试。

相关问题