Skip to content

ffmpeg 音视频处理 ​

FFmpeg 是一个跨平台的音视频处理工具,可通过子进程在 Node.js 中调用。

安装 ​

下载地址:ffmpeg.p2hp.com/download.html

下载后配置环境变量,验证安装:

bash
ffmpeg -version
ffmpeg -version

基本用法 ​

js
const { execSync } = require('child_process')
const { execSync } = require('child_process')

视频转 GIF ​

js
execSync('ffmpeg -i test.mp4 test.gif', { stdio: 'inherit' })
execSync('ffmpeg -i test.mp4 test.gif', { stdio: 'inherit' })

添加水印 ​

js
// drawtext — 添加文字水印
execSync(
  `ffmpeg -i test.mp4 -vf drawtext=text="水印":fontsize=30:fontcolor=white:x=10:y=10 test2.mp4`,
  { stdio: 'inherit' }
)
// drawtext — 添加文字水印
execSync(
  `ffmpeg -i test.mp4 -vf drawtext=text="水印":fontsize=30:fontcolor=white:x=10:y=10 test2.mp4`,
  { stdio: 'inherit' }
)

视频裁剪 ​

js
// -ss 起始时间,-to 结束时间
// ss 写在 -i 前面(速度快但精度低),后面(精度高但速度慢)
execSync('ffmpeg -ss 10 -to 20 -i test.mp4 test3.mp4', { stdio: 'inherit' })
// -ss 起始时间,-to 结束时间
// ss 写在 -i 前面(速度快但精度低),后面(精度高但速度慢)
execSync('ffmpeg -ss 10 -to 20 -i test.mp4 test3.mp4', { stdio: 'inherit' })

提取音频 ​

js
execSync('ffmpeg -i test.mp4 test.mp3', { stdio: 'inherit' })
execSync('ffmpeg -i test.mp4 test.mp3', { stdio: 'inherit' })

去水印 ​

js
// delogo — 删除水印
execSync(
  'ffmpeg -i test2.mp4 -vf delogo=w=120:h=30:x=10:y=10 test3.mp4',
  { stdio: 'inherit' }
)
// delogo — 删除水印
execSync(
  'ffmpeg -i test2.mp4 -vf delogo=w=120:h=30:x=10:y=10 test3.mp4',
  { stdio: 'inherit' }
)

pngquant(PNG 压缩) ​

bash
npm install pngquant
npm install pngquant
js
const { exec } = require('child_process')

// 基本压缩
exec('pngquant 73kb.png --output test.png')

// 指定质量
exec('pngquant 73kb.png --quality=82 --output test.png')

// 指定速度(1 最慢质量最好,10 最快质量稍差)
exec('pngquant 73kb.png --speed=1 --quality=82 --output test.png')
const { exec } = require('child_process')

// 基本压缩
exec('pngquant 73kb.png --output test.png')

// 指定质量
exec('pngquant 73kb.png --quality=82 --output test.png')

// 指定速度(1 最慢质量最好,10 最快质量稍差)
exec('pngquant 73kb.png --speed=1 --quality=82 --output test.png')