由于jave1.0.2找不到h.264格式MP4的转码,找了很多方法之后选择改用FFmpeg进行转码,FFmpeg对服务器的cup消耗较大,还是用云服务器的转码服务好:
public class MediaInfo {
/**
* 视频转码
* @param ffmpegPath 转码工具的存放路径
* @param upFilePath 用于指定要转换格式的文件,要截图的视频源文件
* @param codcFilePath 格式转换后的的文件保存路径
* @return
* @throws Exception
*/
public static boolean executeCodecMP4(String infile,String outfile) throws Exception {
List<String> command=new ArrayList<String>();
//command.add("E://ffmpeg-win64-static/bin/ffmpeg.exe");// 添加转换工具路径
command.add(ConstantCode.WINFFMPEG);
command.add("-i");
command.add(infile);// 添加要转换格式的视频文件的路径
command.add("-y");
command.add("-r");
command.add("20");
command.add("-vcodec");
command.add("libx264");
command.add("-preset");
command.add("ultrafast");
command.add("-profile:v");
command.add("baseline");
command.add("-acodec");
command.add("libmp3lame");
command.add("-strict");
command.add("experimental");
command.add("-s");
command.add("1280*700");
command.add(outfile);
boolean mark = true;
ProcessBuilder builder = new ProcessBuilder();
try {
builder.command(command);
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("exitCode = "+exitCode);
} catch (Exception e) {
mark = false;
System.out.println(e);
e.printStackTrace();
}
return mark;
}
/**
* 音频转码
* @param ffmpegPath 转码工具的存放路径
* @param upFilePath 用于指定要转换格式的文件,要截图的视频源文件
* @param codcFilePath 格式转换后的的文件保存路径
* @return
* @throws Exception
*/
public static boolean executeCodecMP3(String infile,String outfile) throws Exception {
List<String> command=new ArrayList<String>();
command.add(ConstantCode.WINFFMPEG);
command.add("-i");
command.add(infile);// 添加要转换格式的视频文件的路径
command.add("-preset");
command.add("ultrafast");
command.add("-acodec");
command.add("libmp3lame");
command.add(outfile);
boolean mark = true;
ProcessBuilder builder = new ProcessBuilder();
try {
builder.command(command);
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("exitCode = "+exitCode);
} catch (Exception e) {
mark = false;
System.out.println(e);
e.printStackTrace();
}
return mark;
}
public static Long getTime(File file) throws InputFormatException, EncoderException{
Encoder encoder = new Encoder();
MultimediaInfo m = encoder.getInfo(file);
long lengthOfTime = m.getDuration()/1000;
return lengthOfTime;
}
public static void main(String[] args) {
boolean flag = false;
try {
flag = executeCodecMP4("D://myRecord.avi","D://myRecord.mp4");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(flag){
System.out.println("转码成功");
}else{
System.out.println("失败");
}
}
}