使用jave将h264格式视频转MP4
起因:最近做一个高空抛物的项目,其中需要将摄像机抓拍的h264格式视频文件转mp4,进行浏览器在线播放,经过多番资料查找,找到视频编解码工具ffmpeg,利用该工具,直接拼接命令也是可以的,但服务器端还需安装ffmpeg工具,另一种方法就是我要展示的,利用jave(暂且理解为java封装的ffmpeg工具)进行转换。
代码如下:
引入pom依赖:
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId>
<version>2.4.6</version>
</dependency>
<!--linux下引入这个-->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-native-linux64</artifactId>
<version>2.4.6</version>
</dependency>
<!--windows下引入这个-->
<!--<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-native-win64</artifactId>
<version>2.4.6</version>
</dependency>-->
/**
*
* @param filePath 源文件路径
*/
public static void h264ToMp4(String filePath) {
if (StringUtils.isEmpty(filePath) || !filePath.endsWith("h264")) {
return;
}
try {
File file = new File(filePath);
String mp4FilePath = filePath.replace("h264", "mp4");
File mpFile = new File(mp4FilePath);
if (!mpFile.exists()) {
mpFile.createNewFile();
}
//获取文件多媒体类
MultimediaObject sourceFile = new MultimediaObject(file);
VideoAttributes video = new VideoAttributes();
AudioAttributes audio = new AudioAttributes();
//音频编码器
audio.setCodec("libmp3lame");
//位速率又叫比特率,是指在单位时间内可以传输多少数据
audio.setBitRate(new Integer(64000));
//音频的通道数,一般来说 都是单通道和双通道(立体音)
audio.setChannels(new Integer(1));
//是指在数码音频和视频技术应用中,当进行模拟/数码转换时,每秒钟对模拟信号进行取样时的快慢次数
audio.setSamplingRate(new Integer(22050));
//视频编码器
video.setCodec("libx264");
//位速率又叫比特率,是指在单位时间内可以传输多少数据
video.setBitRate(new Integer(800000));
//画面桢速率
video.setFrameRate(new Integer(20));
video.setSize(new VideoSize(1920, 1080));
EncodingAttributes attr = new EncodingAttributes();
attr.setFormat("mp4");
attr.setAudioAttributes(audio);
attr.setVideoAttributes(video);
Encoder encoder = new Encoder();
encoder.encode(sourceFile, mpFile, attr);
} catch (Exception e) {
log.error("h264视频转mp4异常:", e);
}
}