1 packagecom.puxinwangxiao.mts.util;2
3
4 importcom.coremedia.iso.IsoFile;5
6 importjava.io.File;7 importjava.io.IOException;8 importjava.net.UnknownHostException;9
10
11 public classVideoUtil {12
13
14 /**
15 * 获取视频文件的播放长度(mp4、mov格式)16 *@paramvideoPath17 *@return单位为毫秒18 */
19 public static long getMp4Duration(String videoPath) throwsIOException {20 IsoFile isoFile = newIsoFile(videoPath);21 long lengthInSeconds =
22 isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
23 isoFile.getMovieBox().getMovieHeaderBox().getTimescale();24 returnlengthInSeconds;25 }26
27
28 /**
29 * 得到语音或视频文件时长,单位秒30 *@paramfilePath31 *@return
32 *@throwsIOException33 */
34 public static long getDuration(String filePath) throwsIOException {35 String format =getVideoFormat(filePath);36 long result = 0;37 if("wav".equals(format)){38 result =AudioUtil.getDuration(filePath).intValue();39 }else if("mp3".equals(format)){40 result =AudioUtil.getMp3Duration(filePath).intValue();41 }else if("m4a".equals(format)) {42 result =VideoUtil.getMp4Duration(filePath);43 }else if("mov".equals(format)){44 result =VideoUtil.getMp4Duration(filePath);45 }else if("mp4".equals(format)){46 result =VideoUtil.getMp4Duration(filePath);47 }48
49 returnresult;50 }51
52 /**
53 * 得到语音或视频文件时长,单位秒54 *@paramfilePath55 *@return
56 *@throwsIOException57 */
58 public static long getDuration(String filePath,String format) throwsIOException {59 long result = 0;60 if("wav".equals(format)){61 result =AudioUtil.getDuration(filePath).intValue();62 }else if("mp3".equals(format)){63 result =AudioUtil.getMp3Duration(filePath).intValue();64 }else if("m4a".equals(format)) {65 result =VideoUtil.getMp4Duration(filePath);66 }else if("mov".equals(format)){67 result =VideoUtil.getMp4Duration(filePath);68 }else if("mp4".equals(format)){69 result =VideoUtil.getMp4Duration(filePath);70 }71
72 returnresult;73 }74
75
76 /**
77 * 得到文件格式78 *@parampath79 *@return
80 */
81 public staticString getVideoFormat(String path){82 return path.toLowerCase().substring(path.toLowerCase().lastIndexOf(".") + 1);83 }84
85 public static voidmain(String[] args){86 /*
87 //网络文件88 String path = "https://resource.puxinwangxiao.com/gaozhongbibeiwenyanwengushici_5.mp3" ;89 long result = 0;90 try {91 String tmppath = getFileByUrl(path);92 result = getDuration(tmppath);93 } catch (IOException e) {94 e.printStackTrace();95 }96 System.out.println(result);97 */
98
99
100 //本地文件
101 String path = "/Users/liuwen/Downloads/temp/语音测试文件/xiaoshizi.wav";102 long result = 0;103 try{104 result =getDuration(path);105 } catch(IOException e) {106 e.printStackTrace();107 }108 System.out.println(result);109
110 }111 public static String getFileByUrl(String url) throwsUnknownHostException, IOException{112 File tmpFile = File.createTempFile("temp", url.substring(url.lastIndexOf(".")));//创建临时文件
113 Image2Binary.toBDFile(url, tmpFile.getCanonicalPath());114 returntmpFile.getCanonicalPath();115 }116
117 }