node ffmpeg fluent-ffmpeg 安装 及一些命令记录

229 阅读1分钟

1 安装 ffmpeg

brew install ffmpeg

2 安装 fluent-ffmpeg

npm install fluent-ffmpeg

3 创建js文件,写入命令然后 node a.js 执行就好

1 视频转gif

const ffmpeg = require("fluent-ffmpeg");

function convertVideoToGif(videoPath, gifPath, callback) {
  ffmpeg(videoPath)
    .outputOptions([
      "-vf",
      "fps=10,scale=1080:-1:flags=lanczos",
      "-c:v",
      "gif",
      "-f",
      "gif",
    ])
    .save(gifPath)
    .on("end", function () {
      console.log("转换完成");
      callback(null);
    })
    .on("error", function (err) {
      console.log("转换出错: " + err.message);
      callback(err);
    });
}

convertVideoToGif("./m.mp4", "./moment.gif", (err) => {
  if (err) return console.error(err);
  console.log("GIF文件已创建");
});

2 命令转换 ffmpeg -i small.mp4 small.gif

3 视频转 mp3

const ffmpeg = require("fluent-ffmpeg");

function convertMp4ToMp3(inputPath, outputPath) {
  return new Promise((resolve, reject) => {
    ffmpeg(inputPath)
      .output(outputPath)
      .audioCodec("libmp3lame") // 使用 MP3 编解码器
      .on("end", () => {
        console.log("转换完成");
        resolve();
      })
      .on("error", (err) => {
        console.error("转换错误:", err);
        reject(err);
      })
      .run();
  });
}

const inputVideoPath = "./small.mp4"; // MP4 文件路径
const outputAudioPath = "./天梯.mp3"; // 输出 MP3 文件路径

convertMp4ToMp3(inputVideoPath, outputAudioPath)
  .then(() => console.log("MP4 转 MP3 成功"))
  .catch((err) => console.error("MP4 转 MP3 失败:", err));