使用ffmpeg.js压缩视频失效,求前端视频压缩替代库
问题分析与解决方案
原代码的核心问题
- FFmpeg实例不共享:
compressVideo和downloadFile分别创建独立的FFmpeg实例,两者文件系统完全隔离,导致downloadFile无法读取到压缩后的文件。 - 缺少错误处理与日志:未捕获FFmpeg执行过程中的错误,也未开启日志输出,无法定位压缩失败的具体原因。
- 核心资源加载缺失:@ffmpeg/ffmpeg需要指定核心文件加载路径,否则现代浏览器中可能因资源加载失败导致功能失效。
修复后的示例代码
<template> <div> <input type="file" @change="handleFileInputChange" accept="video/*"> <video ref="video" controls></video> </div> </template> <script> import { FFmpeg } from '@ffmpeg/ffmpeg'; import { toBlobURL } from '@ffmpeg/util'; export default { data() { return { ffmpeg: null } }, async mounted() { this.ffmpeg = new FFmpeg(); // 指定核心文件加载路径,避免跨域或资源找不到问题 await this.ffmpeg.load({ coreURL: await toBlobURL('https://unpkg.com/@ffmpeg/core@0.12.6/dist/ffmpeg-core.js', 'text/javascript'), }); // 开启日志输出便于调试 this.ffmpeg.on('log', ({ message }) => console.log(message)); }, methods: { async handleFileInputChange(event) { const file = event.target.files[0]; if (!file) return; const video = this.$refs.video; const url = URL.createObjectURL(file); video.src = url; const inputVideoPath = 'input.mp4'; const outputVideoPath = 'compressed_output.mp4'; console.log("Compressing video..."); try { await this.compressVideo(file, inputVideoPath, outputVideoPath); console.log("Compression completed."); const compressedBlob = await this.downloadFile(outputVideoPath); video.src = URL.createObjectURL(compressedBlob); } catch (err) { console.error("Compression failed:", err); } }, async compressVideo(file, inputVideoPath, outputVideoPath) { await this.ffmpeg.writeFile(inputVideoPath, file); // 添加音频编码参数避免生成无音视频 await this.ffmpeg.exec([ '-i', inputVideoPath, '-vcodec', 'libx264', '-crf', '28', '-acodec', 'aac', '-b:a', '128k', outputVideoPath ]); }, async downloadFile(filePath) { const data = await this.ffmpeg.readFile(filePath); return new Blob([data.buffer], { type: 'video/mp4' }); } } }; </script> <style scoped> </style>
推荐的替代视频压缩库
1. browser-video-compression
- 封装了MediaRecorder和FFmpeg.wasm,API简洁,支持自定义分辨率、比特率等参数。
- 无需手动处理FFmpeg实例,直接传入文件即可完成压缩,适合快速集成。
2. video-converter-js
- 基于FFmpeg.wasm构建,内置低/中/高质量等预设压缩配置,同时支持自定义命令。
- 提供进度回调,便于显示压缩进度条,提升用户体验。
3. 原生MediaRecorder API
- 无需引入第三方库,直接使用浏览器原生API转码压缩。
- 支持编码为webm或mp4格式,虽压缩参数灵活性不如FFmpeg,但胜在轻量无依赖。
内容的提问来源于stack exchange,提问作者John Mark
相关产品推荐
相关产品推荐

