最近公司要求项目中博客功能添加视频上传功能,可是用户一般上传的格式都不是flash格式,因此我需要将用户上传的视频格式进行转换为flash格式,这样就不需要安装视频插件就可以播放视频了。为此,在网上搜了很多资料,做法最多的就是采用第三方开源的软件ffmpeg和mencoder进行格式转换,话不多说,贴代码。
import java.io.*;
public class TransferToFlv {
public boolean ffmpegTransfer(String infile,String outfile) {
String base = "/home/files/soft/ffmpeg/bin/";
String avitoflv = "ffmpeg -i "+infile+" -ab 128 -acodec libmp3lame -ac 1 -ar 22050 -r 29.97 -b 512 -y -f flv "+outfile;
try {
Runtime rt = Runtime.getRuntime();
// Process proc = rt.exec(avitoflv);
Process proc = rt.exec(new String[]{"sh","-c",avitoflv});
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();
return false;
}
return true;
}
}