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

Electron渲染进程使用FFmpeg报错:ffmpeg(...).input不是函数求解决

问题:Electron渲染进程调用FFmpeg时出现ffmpeg(...).input is not a function错误

问题场景

在Electron应用的preload.js中尝试暴露FFmpeg模块:

const { contextBridge, ipcRenderer } = require('electron');
const ffmpegStatic = require('ffmpeg-static');
const ffmpeg = require('fluent-ffmpeg');
// make ffmpeg available as a function in the renderer process
contextBridge.exposeInMainWorld('ffmpeg', () => ffmpeg(ffmpegStatic.path));

在renderer.js中调用:

video.addEventListener('change', (event) => {
    const file = event.target.files[0];
    const filePath = file.path;
    const fileName = file.name;
    const fileExt = fileName.split('.').pop();
    const newFileName = fileName.replace(fileExt, 'mp4');
    const newFilePath = filePath.replace(fileName, newFileName);

    // Run FFmpeg
    ffmpeg()
        // Input file
        .input(filePath)
        // Audio bit rate
        .outputOptions('-ab', '192k')
        // Output file
        .saveToFile(newFilePath)
        // Log the percentage of work completed
        .on('progress', (progress) => {
            if (progress.percent) {
                console.log(`Processing: ${Math.floor(progress.percent)}% done`);
            }
        })
        // The callback that is run when FFmpeg is finished
        .on('end', () => {
            console.log('FFmpeg has finished.');
        })
        // The callback that is run when FFmpeg encountered an error
        .on('error', (error) => {
            console.error(error);
        });
});

运行后控制台报错:Uncaught TypeError: ffmpeg(...).input is not a function at HTMLInputElement

错误原因

误用了fluent-ffmpeg的API:

  • fluent-ffmpeg不支持通过ffmpeg(ffmpegStatic.path)传入路径,正确的路径配置方式是调用ffmpeg.setFfmpegPath()提前设置。
  • 之前的暴露方式返回的是错误的调用结果,并非合法的FFmpeg命令实例,因此不存在input方法。

修复方案

修改preload.js

先配置FFmpeg路径,再将正确的ffmpeg工厂函数暴露给渲染进程:

const { contextBridge } = require('electron');
const ffmpegStatic = require('ffmpeg-static');
const ffmpeg = require('fluent-ffmpeg');

// 提前设置FFmpeg可执行文件的路径
ffmpeg.setFfmpegPath(ffmpegStatic.path);

// 将配置好的ffmpeg工厂函数暴露到渲染进程
contextBridge.exposeInMainWorld('ffmpeg', ffmpeg);

保持renderer.js不变

现在ffmpeg()会返回合法的命令实例,可正常链式调用input、outputOptions等方法。

额外注意事项

  • 确保Electron的contextIsolation配置为true(默认开启),这是使用contextBridge的前提。
  • 若担心直接暴露整个ffmpeg对象有安全风险,可以仅封装业务需要的方法(如创建命令、设置输入输出等)后再暴露,上述方案已能满足基础转码需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:55:33