mp4视频电脑能播放,视频html播放不了,转H264

135 阅读1分钟

前提:今天周五,下周要验收了,对接的另外一个系统的视频由实时变下载mp4形式展现。 本来以为很快能搞完,后面发现视频播放不了。 原因:浏览器支持H264的编码格式,不支持H265的。

解决方法把视频转H264编码格式:

1.[下载ffmpeg ](Builds - CODEX FFMPEG @ gyan.dev)

image.png

2.解压

image.png

3.建如图video.js在node环境下跑 node video.js ,注意改步骤2的路径

const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs');
const path = require('path');

// 设置FFmpeg路径,如果FFmpeg不在系统路径中
ffmpeg.setFfmpegPath('C:\\ffmpeg\\bin\\ffmpeg.exe'); // 放刚刚解压的的路径

const inputFolderPath = 'D:\\shan\\放视频的目录'; // 输入文件夹路径
const outputFolderPath = 'D:\\shan\\新视频'; // 输出文件夹路径

// 确保输出文件夹存在,如果不存在则创建
if (!fs.existsSync(outputFolderPath)) {
  fs.mkdirSync(outputFolderPath, { recursive: true });
}

// 读取文件夹中的所有文件
fs.readdir(inputFolderPath, (err, files) => {
  if (err) {
    return console.error('无法扫描目录: ' + err);
  } 

  // 过滤出视频文件
  const videoFiles = files.filter(file => file.endsWith('.mp4') || file.endsWith('.avi')); // 根据需要添加更多扩展名

  videoFiles.forEach(videoFile => {
    const inputFilePath = path.join(inputFolderPath, videoFile);
    const outputFilePath = path.join(outputFolderPath, videoFile);

    ffmpeg(inputFilePath)
      .videoCodec('libx264') // 设置视频编解码器为H.264
      .on('start', (commandLine) => {
        console.log(`Spawned Ffmpeg with command: ${commandLine}`);
      })
      .on('progress', (progress) => {
        console.log(`${videoFile}: Processing: ${progress.percent}% done`);
      })
      .on('end', () => {
        console.log(`${videoFile}: Conversion finished!`);
      })
      .on('error', (err) => {
        console.error(`${videoFile}: Error during conversion: ${err.message}`);
      })
      .save(outputFilePath);
  });
});

4.等着跑完就可以了

image.png