FFMpeg video duration

时间:2023-07-31 17:22:48

1. 代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; public class FFMPEGDurationer {
private static final String infoPath = "c:\\MediaInfo\\"; public static String inform(String fileName) {
fileName = fileName.replaceAll("/", "\\\\");
String cmd = infoPath + "ffmpeg -i " + fileName;
try {
Process proc = Runtime.getRuntime().exec(cmd);
InputStream out = proc.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(out));
String line = "";
StringBuffer sb = new StringBuffer();
if(in.readLine()!= null){
while((line=in.readLine()) != null){
if(line.equals("")||line.indexOf("Duration:")==-1)
continue; sb.append(line.trim());
}
} return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
} } public static long getDuration(String fileName){
String info = inform(fileName);
String str = select(info);
return parseLong(str);
} private static String select(String info){
String[] infos = info.split(",");
if(infos.length==0)
return ""; for(int i=0;i<infos.length;i++){
String str = infos[i].trim();
if(str.indexOf("Duration")!=-1){
String dur = str.substring(str.indexOf(":")+2);
return dur;
}
} return "";
} /**
*duration String eg. 8s 160ms / 1h 37mn;
*/
public static long parseLong(String duration){
if(duration==null||duration.equals(""))
return 0;
if("N/A".equals(duration))
return 0; int ms = 0;
int p = duration.lastIndexOf(".");
if(p!=-1){
String tmp = duration.substring(p+1);
tmp = "0." + tmp;
ms = (int)(Float.parseFloat(tmp)*1000);
}
int fr = ms*25/1000;
String frstr = String.format("%02d", fr);
try {
String _dur = duration.substring(0,p) + ":" + frstr;
return Long.parseLong(_dur);
} catch (Exception e) {
return 0;
} } public static void main(String[] args) {
long str = FFMPEGDurationer.getDuration("d:\\a.wmv");
// long str = FFMPEGDurationer.getDuration("x:\\av\\555_MPEG.m2t");
System.out.println(str);
} }

2. 软件安装 FFmpeg 路径(c:/MediaInfo)