1. 業(yè)務(wù)場景
業(yè)務(wù)需求:對上傳的視頻顯示該時(shí)長。
2. FFmpeg框架處理視頻信息
FFmpeg官網(wǎng):http://ffmpeg.org/
3. 代碼實(shí)現(xiàn)
3.1 windows安裝FFmpeg
我在這篇五分鐘JAVA代碼教會你:FFmpeg實(shí)現(xiàn)視頻試看(window版本)中寫的十分詳細(xì),在windows/Linux安裝FFmepg,此處我就不過多闡述了。
3.2 執(zhí)行口令查看視頻信息
在window中安裝FFmpeg后,在cmd執(zhí)行獲取時(shí)長的命令即可:
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
執(zhí)行效果,如下:

3.3 Java解析信息并返回時(shí)長
通過FFmpeg執(zhí)行命令行,獲取返回的視頻信息,通過java篩選到視頻信息的目標(biāo)數(shù)據(jù),進(jìn)行返回即可。
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("視頻時(shí)長:"+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("視頻時(shí)長:"+timeLength);
}
/**
*獲取視頻時(shí)間
* @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();
//從視頻信息中解析時(shí)長
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+",視頻時(shí)長:"+m.group(1)+", 開始時(shí)間:"+m.group(2)+",比特率:"+m.group(3)+"kb/s");
return m.group(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
執(zhí)行效果如下:

視頻源文件:

?文章來源地址http://www.zghlxwxcb.cn/news/detail-706259.html
原文?FFmpeg框架系列:獲取視頻時(shí)長_ffmpeg視頻合成時(shí)長代碼_瓜仙人的博客-CSDN博客
★文末名片可以免費(fèi)領(lǐng)取音視頻開發(fā)學(xué)習(xí)資料,內(nèi)容包括(FFmpeg ,webRTC ,rtmp ,hls ,rtsp ,ffplay ,srs)以及音視頻學(xué)習(xí)路線圖等等。
見下方!↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓文章來源:http://www.zghlxwxcb.cn/news/detail-706259.html
?
到了這里,關(guān)于FFmpeg框架系列:獲取視頻時(shí)長的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!