1
javascript
npm install @ffmpeg/ffmpeg@0.10.1 @ffmpeg/core@0.10.0
2
node_modules@ffmpeg\ffmpeg\package.json添加
javascript
"exports": {
"./dist/ffmpeg.min.js": "./dist/ffmpeg.min.js"
},
3
导入使用:
javascript
import { createFFmpeg, fetchFile } from "@ffmpeg/ffmpeg/dist/ffmpeg.min.js";
4
FFmpegCore.js SharedArrayBuffer is not defined
javascript
浏览器快捷方式的目标最后面加 --enable-features=SharedArrayBuffer
5
示例
javascript
import { createFFmpeg, fetchFile } from "@ffmpeg/ffmpeg/dist/ffmpeg.min.js";
module.exports = {
logs: '',
init() {
window.ffmpeg = createFFmpeg({
log: true, logger: (...args) => {
for (let i = 0; i < args.length; i++) {
this.logs = this.logs + JSON.stringify(args[i])
}
},
});
},
async compressVideo(fileurl, callback) {
this.logs = ''
let ffmpeg = window.ffmpeg
if (!ffmpeg.isLoaded()) {
await ffmpeg.load();
}
let filename = `${new Date().getTime()}.mp4`
ffmpeg.FS('writeFile', filename, await fetchFile(fileurl));
await ffmpeg.run('-i', filename);
const durationMatch = this.logs.match(/Duration: (\d+:\d+:\d+\.\d+)/);
const bitrateMatch = this.logs.match(/bitrate:\s+(\d+)\s+kb\/s/);
const duration = durationMatch ? this.parseDuration(durationMatch[1]) : 0;
const bitrate = bitrateMatch ? parseInt(bitrateMatch[1]) * 1000 : 0; // 转换为 bps
console.log(`视频时长: ${duration} 秒`);
console.log(`原编码率: ${bitrate} bps`);
ffmpeg.FS('unlink', filename);
},
parseDuration(durationString) {
const parts = durationString.split(':');
return (parseInt(parts[0]) * 3600) + (parseInt(parts[1]) * 60) + parseFloat(parts[2]);
}
}