背景介绍:
web开发中涉及到视频播放的前端一般会使用h5的video标签对后端提供的视频文件url直接加载进行播放,虽然视频文件后缀都是mp4,但并非所有视频文件的编码格式都支持用video播放,目前支持的格式有以下几种:
MP4 = MPEG4文件使用H264视频编解码器和AAC音频编解码器
WebM = WebM文件使用VP8视频编解码器和Vorbis音频编解码器
Ogg = Ogg文件使用Theora视频编解码器和Vorbis音频编解码器
当视频文件不支持video标签播放时需要将其格式用编码工具转化为支持的格式。
本文是通过Java调用FFmpeg命令将MPEG编码格式转化为H264格式,当视频文件比较少时可以采用播放器软件(QQ影音就可以)来转。
Linux下安装FFmpeg
- 先安装yasm
# 下载yasm
wget http://www.tortall.net/projects/yasm/releases/yasm-1.3.0.tar.gz
# 解压
tar -xzvf yasm-1.3.0.tar.gz
# 配置安装
cd yasm-1.3.0
./configure
make
make install
- 编译安装H264模块
# 下载x264
git clone https://code.videolan.org/videolan/x264.git
# 切换到x264目录
cd x264
# --prefix=/usr/local/x264 指定安装目录,这里不要指定,否则会出现库找不到的问题
# 执行配置
./configure --enable-shared --enable-static --enable-yasm
# 编译安装
make & make install
- 安装FFmpeg
# 下载
wget https://ffmpeg.org/releases/ffmpeg-4.2.2.tar.bz2
tar -jxvf ffmpeg-4.2.2.tar.bz2
cd ffmpeg-4.2.2
# 安装
./configure --enable-gpl --enable-libx264
make & make insatll
注:以上安装都没有指定安装路径,即为默认路径,无需为FFmpeg添加系统变量,找不到h264模块时应该做入下配置项
- 修改系统库的配置
vim vim /etc/ld.so.conf
# 添加以下行
/usr/local/lib
# 保存退出后执行以下命名使lib库生效
ldconfig
- 测试ffmpeg是否安装成功
ffmpeg -version
显示如下即为安装成功
Java调用系统FFmpeg命令实现转码
/**
* 调用系统命令转码每个文件
* @param inputFile 输入视频文件路径
* @param outputDir 输出目录路径
*/
private static void transferToH264(File inputFile,File outputDir){
if (!outputDir.exists()){
outputDir.mkdirs();
}
String outputFile = outputDir.getPath()+"/"+inputFile.getParent();
File outDir = new File(outputFile);
if(!outDir.exists()){
outDir.mkdirs();
}
System.out.println(outputFile+"/"+inputFile.getName());
outputFile = outputFile+"/"+inputFile.getName();
String command = "ffmpeg -threads 5 -i " + inputFile.getAbsolutePath() + " -vcodec libx264 -preset ultrafast -r 29 -s 1920x1080 "+outputFile;
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ( (line = br.readLine()) != null)
System.out.println(line);
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
}
FFmpeg常用命令以及参数
-i 指定要转换视频的源文件
-s 视频转换后视频的分辨率
-vcodec 视频转换时使用的编解码器(-codecs)
-r 视频转换换的桢率(默认25桢每秒)
-b 视频转换换的bit率
-ab 音频转换后的bit率(默认64k)
-acodec 制定音频使用的编码器(-codecs)
-ac 制定转换后音频的声道
-ar 音频转换后的采样率
-an 禁用音频
-vn 禁用视频
-acodec copy 复制音频,不转码
-vcodec copy 复制视频,不转码
# 设置参数转
ffmpeg -i 88885.mp4 -vcodec h264 -r 29 -b:v 43382k 88885_h264.mp4
# 直接转码
# 视频文件转化为h264编码格式,直接转为h264编码格式
ffmpeg -i 88885.mp4 -vcodec h264 88885_h264.mp4
- FFmpeg转码速率问题
转码默认参数比较慢,可以指定以下参数来选择合适的速率。
ultrafast:最快的编码方式
superfast:超级快速的编码方式
veryfast:非常快速的编码方式
faster:稍微快速的编码方式
fast:快速的编码方式
medium:折中的编码方式
slow:慢的编码方式
slower:更慢的编码方式
veryslow:非常慢的编码方式
placebo:最慢的编码方式
更多参数请参考这篇文章和官方提供的文档
https://www.jianshu.com/p/49fcae61e58c