3 import java.io.BufferedReader;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.util.regex.Matcher;
9 import java.util.regex.Pattern;
15 public final class FfmpegUtil {
17 private static final Pattern PATTERN_DURATION = Pattern.compile("Duration: (\\d+):(\\d+):(\\d+)");
18 private final File ffmpegPath;
19 private final File targetPath;
20 private String execResultCache;
22 public FfmpegUtil(File ffmpeg, File target) {
23 this.ffmpegPath = ffmpeg;
24 this.targetPath = target;
27 public int getDuration() throws IOException {
28 final String res = getExecResult();
29 final Matcher m = PATTERN_DURATION.matcher(res);
31 final int hour = Integer.parseInt(m.group(1));
32 final int min = Integer.parseInt(m.group(2));
33 final int sec = Integer.parseInt(m.group(3));
34 return ((hour * 60) + min) * 60 + sec;
36 throw new IOException("Can Not Get Duration");
40 private String getExecResult() throws IOException {
41 if (execResultCache != null) {
42 return execResultCache;
44 final ProcessBuilder pb = new ProcessBuilder(ffmpegPath.getPath(), "-i", targetPath.getPath());
45 final Process process = pb.start();
46 final InputStream es = process.getErrorStream();
47 final BufferedReader reader = new BufferedReader(new InputStreamReader(es));
48 final StringBuilder sb = new StringBuilder();
50 while ((str = reader.readLine()) != null) {
53 final String res = sb.toString();
54 System.out.println(res);
55 execResultCache = res;