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
相关产品推荐
相关产品推荐

