Skip to content

使用 ffmpeg 转码视频 - 并且在 web 播放视频

使用 ffmpeg 将视频流转码后使用 Media Source Extensions 播放

遇到问题

1. 多字幕、多音频轨道转码后播放失败

https://github.com/Dash-Industry-Forum/dash.js/issues/2864

使用 ffmpeg 将 8 通道音频降采样为 2 通道音频

bash
ffmpeg -i input-audio.mp4 -ac 2 output-stereo-audio.mp4

其中:

  • input-audio.mp4 是您的原始 8 通道音频文件。
  • -ac 2 是一个参数,它将音频通道设置为 2,这意味着音频将被转换为立体声。
  • output-stereo-audio.mp4 是输出的 2 通道(立体声)音频文件。

修复之前

js
let commandArgs = [
  "-thread_queue_size",
  "1024",
  "-headers",
  `Authorization: Bearer ${token}`,
  "-i",
  newUrl,
  // 'pipe:0', // Read from stdin (video input)
  "-f",
  "lavfi",
  "-i",
  "anullsrc=r=44100:cl=stereo", // Generate silent audio
  "-c:v",
  "libx264",
  "-preset",
  "veryfast",
  "-c:a",
  "aac",
  "-movflags",
  "frag_keyframe+empty_moov+default_base_moof",
  "-shortest", // Finish encoding when the shortest input stream ends
  "-f",
  "mp4", // Specify output format as mp4
  "pipe:1", // Write to stdout
];

if (isAudio) {
  // 如果是音频,移除一些视频相关的参数并进行必要的调整
  commandArgs = [
    "-thread_queue_size",
    "1024",
    "-i",
    "pipe:0",
    "-c:a",
    "aac",
    "-f",
    "mp4",
    "pipe:1",
  ];
}

this.ffmpegProcess = spawn(ffmpegPath, commandArgs, {
  // stdio: ['ignore', 'pipe', 'pipe'],
  maxBuffer: 1024 * 1024 * 1024, // 1 GB
});

修复后 增加了 '-ac', '2', 参数

js
let commandArgs = [
  "-thread_queue_size",
  "1024",
  "-headers",
  `Authorization: Bearer ${token}`,
  "-i",
  newUrl,
  // '-b:v',
  // '2M', // 限制视频比特率为2 Mbps
  // '-sn', // 这行代码会禁用所有的字幕流
  "-f",
  "lavfi",
  "-i",
  "anullsrc=r=44100:cl=stereo", // Generate silent audio
  "-ac",
  "2",
  "-c:v",
  "libx264",
  "-preset",
  "veryfast",
  "-c:a",
  "aac",
  "-movflags",
  "frag_keyframe+empty_moov+default_base_moof",
  "-shortest", // 当最短的输入流结束时完成编码
  "-f",
  "mp4", // 指定输出格式为mp4
  "pipe:1", // 写入stdout
];