FFmpeg框架系列:獲取視頻時長
- 1. 業務場景
- 2. FFmpeg框架處理視頻資訊
- 3. 代碼實作
- 3.1 windows安裝FFmpeg
- 3.2 執行口令查看視頻資訊
- 3.3 Java決議資訊并回傳時長
- 4. 貼出完成Demo
1. 業務場景
業務需求:對上傳的視頻顯示該時長,
2. FFmpeg框架處理視頻資訊
FFmpeg官網:http://ffmpeg.org/
3. 代碼實作
3.1 windows安裝FFmpeg
我在這篇五分鐘JAVA代碼教會你:FFmpeg實作視頻試看(window版本)中寫的十分詳細,在windows/Linux安裝FFmepg,此處我就不過多闡述了,
3.2 執行口令查看視頻資訊
在window中安裝FFmpeg后,在cmd執行獲取時長的命令即可:
F:\ffmpegDemo\ffmpeg\bin\ffmpeg.exe -i F://ffmpegDemo//test.mp4
PS:解壓在windows本地的ffmpeg程式F:\ffmpegDemo\ffmpeg\bin\ffmpeg.exe以及存放在windows本地視頻:F://ffmpegDemo//test.mp4
執行效果,如下:

3.3 Java決議資訊并回傳時長
通過FFmpeg執行命令列,獲取回傳的視頻資訊,通過java篩選到視頻資訊的目標資料,進行回傳即可,
public static void main(String[] args) {
String timeLength = getVideoTime("F://ffmpegDemo//test.mp4","F:\\ffmpegDemo\\ffmpeg\\bin\\ffmpeg.exe");
if(timeLength.length()>0){//字串截取
timeLength =timeLength.substring(0,timeLength.indexOf("."));
}
System.out.println("視頻時長:"+timeLength);
}

4. 貼出完成Demo
public class ExecWindowCMD {
public static void main(String[] args) {
String timeLength = getVideoTime("F://ffmpegDemo//test.mp4","F:\\ffmpegDemo\\ffmpeg\\bin\\ffmpeg.exe");
if(timeLength.length()>0){//字串截取
timeLength =timeLength.substring(0,timeLength.indexOf("."));
}
System.out.println("視頻時長:"+timeLength);
}
/**
*獲取視頻時間
* @param video_path 視頻路徑
* @param ffmpeg_path ffmpeg安裝路徑
* @return
*/
public static String getVideoTime(String video_path, String ffmpeg_path) {
List<String> commands = new java.util.ArrayList<String>();
commands.add(ffmpeg_path);
commands.add("-i");
commands.add(video_path);
System.out.println("命令列:"+ffmpeg_path+" -i "+video_path);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commands);
final Process p = builder.start();
//從輸入流中讀取視頻資訊
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
//從視頻資訊中決議時長
String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
Pattern pattern = Pattern.compile(regexDuration);
Matcher m = pattern.matcher(sb.toString());
if (m.find()) {
//System.out.println(video_path+",視頻時長:"+m.group(1)+", 開始時間:"+m.group(2)+",位元率:"+m.group(3)+"kb/s");
return m.group(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
執行效果如下:

視頻源檔案:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/121280.html
標籤:其他
