java 代碼獲取視頻時長
需要引入jar包 下載地址
http://www.sauronsoftware.it/projects/jave/download.php
1 package test; 2 3 import java.io.File; 4 import java.math.BigDecimal; 5 6 import it.sauronsoftware.jave.Encoder; 7 import it.sauronsoftware.jave.MultimediaInfo; 8 9 10 public class ReadVideo { 11 /** 12 * 讀取視頻時長 13 * @param videoPath 視頻路徑 14 * @return 15 */ 16 public static String readVideo(String videoPath) { 17 String durationStr = ""; 18 File file = new File(videoPath); //videoPath傳入值("D:\\666.mp4") 19 Encoder encoder = new Encoder(); 20 long sum = 0; 21 try { 22 MultimediaInfo m = encoder.getInfo(file); 23 sum = m.getDuration()/1000; //時長sum單位:秒 24 25 } catch (Exception e) { 26 e.printStackTrace(); 27 } 28 double sum1 = (double) sum; 29 System.out.println("視頻時長總秒數:"+sum1); 30 31 BigDecimal duration =BigDecimal.valueOf(sum); 32 durationStr = durationFormatToString(duration); 33 System.out.println("視頻時長:"+durationStr); 34 35 return durationStr; 36 } 37 38 /** 39 * 將視頻時長轉換成"00:00:00.000"的字符串格式 40 * @param duration 視頻時長(單位:秒) 41 * @return 42 */ 43 public static String durationFormatToString(BigDecimal duration) 44 { 45 BigDecimal nine = BigDecimal.valueOf(9); 46 BigDecimal sixty = BigDecimal.valueOf(60); 47 48 BigDecimal second = duration.divideAndRemainder(sixty)[1]; 49 BigDecimal minute = duration.subtract(second).divide(sixty).divideAndRemainder(sixty)[1]; 50 BigDecimal hour = duration.subtract(second).divideToIntegralValue(BigDecimal.valueOf(3600)); 51 52 String str = ""; 53 if (hour.compareTo(nine)>0) 54 { 55 str += hour.intValue() + ":"; 56 } 57 else 58 { 59 str += "0" + hour.intValue() + ":"; 60 } 61 if (minute.compareTo(nine)>0) 62 { 63 str += minute.intValue() + ":"; 64 } 65 else 66 { 67 str += "0" + minute.intValue() + ":"; 68 } 69 if (second.compareTo(nine)>0) 70 { 71 str += second.intValue() + ".000"; 72 } 73 else 74 { 75 str +="0"+ second.intValue() + ".000"; 76 } 77 return str; 78 } 79 80 }
需要引入jar包 下載地址
http://www.sauronsoftware.it/projects/jave/download.php