Node.js + FFmpeg 多媒体处理
FFmpeg 是一个跨平台开源多媒体处理工具,配合 Node.js child_process 可实现视频/音频处理。
安装
从 ffmpeg.org 下载对应系统版本,配置环境变量后验证:
bash
ffmpeg -version常用操作(通过 execSync 调用)
1. 视频转 GIF
js
const { execSync } = require('child_process')
execSync(`ffmpeg -i test.mp4 test.gif`, { stdio: 'inherit' })-i 表示输入文件。
2. 添加文字水印
js
execSync(`ffmpeg -i test.mp4 -vf drawtext=text="水印文字":fontsize=30:fontcolor=white:x=10:y=10 output.mp4`, { stdio: 'inherit' })-vf 即 video filter,drawtext 添加文字。
3. 视频裁剪(截取片段)
js
execSync(`ffmpeg -ss 10 -to 20 -i test.mp4 output.mp4`, { stdio: 'inherit' })-ss起始时间(秒)-to结束时间(秒)
-ss放-i前面:解析快但精度可能不准;放-i后面:精度准但解析慢
4. 提取音频
js
execSync(`ffmpeg -i test.mp4 output.mp3`, { stdio: 'inherit' })5. 去水印(delogo)
js
execSync(`ffmpeg -i input.mp4 -vf delogo=w=120:h=30:x=10:y=10 output.mp4`, { stdio: 'inherit' })w/h 宽高,x/y 水印坐标。
{ stdio: 'inherit' }表示将 FFmpeg 的输出直接打印到终端,方便查看进度。