最近接到一个老项目,由于老项目之前适配的是ie浏览器。该老项目中有很多wmv和avi格式的视频。最近需要更换视频其他浏览器访问,需要对除ie浏览器的其他浏览器进行适配。ie浏览器播放视频没有任何问题,但是在主流浏览器中,无法识别<embed>标签
,只支持<video>、<audio>标签
,然而这些标签支持的视频格式为主流的mp4格式的视频。导致兼容性问题,无法播放,以及主流浏览器无法播放非mp4格式的视频。尝试了很多,查阅了很多资料,前端无法解决该问题,最后尝试使用后端来解决该问题。通过java调用ffmpeg来对已经存储在系统中的视频进行自主的格式转换为mp4,前端通过判断是否为ie浏览器,而执行对应的js脚本。如果发现为非ie浏览器,并且视频为非mp4格式的视频,则主动调用后台接口,对该视频进行格式转换,同时更新数据库存储视频的目标位置,之后再访问该视频时,就查询到的是mp4格式的视频,就无需再做格式转换操作了。
文末附相关安装包、ffmpeg相关命令介绍
ffmpeg
ffmpeg是一个支持多个格式视频转换(包括asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv格式)的软件。在windows和linux环境下使用的方式不同。
首先需要下载ffmpeg软件,解压之后将ffmpeg.exe放入到项目目录中。通过java去调用该程序,执行命令对目标视频进行格式转换。
相关java代码
ConvertVideo
是接收需要转换的视频的类。需要注意的是,其中window环境下获取的ffmpeg目录与linux环境下获取ffmpeg目录是不同的。
public class ConvertVideo {
public static Boolean convertVedio(String inputPath) throws FFmpegException {
if (inputPath.substring(inputPath.lastIndexOf(".")).equals(".mp4") || inputPath.substring(inputPath.lastIndexOf(".")).equals(".MP4")){
return true;
}
String ffmpegPath = getFfmpegPath();
String outputPath = getOutputPath(inputPath);
if (new File(outputPath).exists()){
return true;
}
return FFmpegUtil.ffmpeg(ffmpegPath, inputPath, outputPath);
}
/**
* 获取ffmpeg执行文件的路径
*
* @return
*/
private static String getFfmpegPath() {
// windows环境
return new Object(){
public String getPath(){
return this.getClass().getResource("/").getPath().replaceAll("WEB-INF/classes/", "")+"ffmpeg/";
}
}.getPath();
// linux环境
//return "/opt/ffmpeg/ffmpeg-release.4.1/";
}
/**
* 获取输出文件名
*
* @param inputPath
* @return
*/
private static String getOutputPath(String inputPath) {
return inputPath.substring(0, inputPath.lastIndexOf(".")) + ".mp4";
}
public static String getNewFileUrl(String inputPath) {
return inputPath.substring(0, inputPath.lastIndexOf("."