java 读取音频/视频 文件时长

  • 支持mp3,mp4,mov,m4a,wav 格式文件

源码

pom文件

 1   <!-- mp3文件支持(如语音时长)-->
 2     <dependency>
 3       <groupId>org</groupId>
 4       <artifactId>jaudiotagger</artifactId>
 5       <version>2.0.1</version>
 6     </dependency>
 7  
 8     <!-- mp4文件支持(如语音时长)-->
 9     <dependency>
10       <groupId>com.googlecode.mp4parser</groupId>
11       <artifactId>isoparser</artifactId>
12       <version>1.1.22</version>
13     </dependency>

工具类

  1 package com.puxinwangxiao.mts.util;
  2 
  3 
  4 import com.coremedia.iso.IsoFile;
  5 
  6 import java.io.File;
  7 import java.io.IOException;
  8 import java.net.UnknownHostException;
  9 
 10 
 11 public class VideoUtil {
 12 
 13 
 14     /**
 15      * 获取视频文件的播放长度(mp4、mov格式)
 16      * @param videoPath
 17      * @return 单位为毫秒
 18      */
 19     public static long getMp4Duration(String videoPath) throws IOException {
 20         IsoFile isoFile = new IsoFile(videoPath);
 21         long lengthInSeconds =
 22                 isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
 23                         isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
 24         return lengthInSeconds;
 25     }
 26 
 27 
 28     /**
 29      * 得到语音或视频文件时长,单位秒
 30      * @param filePath
 31      * @return
 32      * @throws IOException
 33      */
 34     public static long getDuration(String filePath) throws IOException {
 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         return result;
 50     }
 51 
 52     /**
 53      * 得到语音或视频文件时长,单位秒
 54      * @param filePath
 55      * @return
 56      * @throws IOException
 57      */
 58     public static long getDuration(String filePath,String format) throws IOException {
 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         return result;
 73     }
 74 
 75 
 76     /**
 77      * 得到文件格式
 78      * @param path
 79      * @return
 80      */
 81     public static String getVideoFormat(String path){
 82         return  path.toLowerCase().substring(path.toLowerCase().lastIndexOf(".") + 1);
 83     }
 84 
 85     public static void main(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) throws UnknownHostException, IOException{
112         File tmpFile = File.createTempFile("temp", url.substring(url.lastIndexOf(".")));//创建临时文件
113         Image2Binary.toBDFile(url, tmpFile.getCanonicalPath());
114         return tmpFile.getCanonicalPath();
115     }
116 
117 }
  1 package com.puxinwangxiao.mts.util;
  2 
  3 
  4 import org.jaudiotagger.audio.AudioFileIO;
  5 import org.jaudiotagger.audio.mp3.MP3AudioHeader;
  6 import org.jaudiotagger.audio.mp3.MP3File;
  7 
  8 
  9 import javax.sound.sampled.AudioFormat;
 10 import javax.sound.sampled.AudioInputStream;
 11 import javax.sound.sampled.AudioSystem;
 12 import java.io.File;
 13 
 14 public class AudioUtil {
 15 
 16 
 17     /**
 18      * 获取语音文件播放时长(秒) 支持wav 格式
 19      * @param filePath
 20      * @return
 21      */
 22     public static Float getDuration(String filePath){
 23         try{
 24 
 25             File destFile = new File(filePath);
 26             AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(destFile);
 27             AudioFormat format = audioInputStream.getFormat();
 28             long audioFileLength = destFile.length();
 29             int frameSize = format.getFrameSize();
 30             float frameRate = format.getFrameRate();
 31             float durationInSeconds = (audioFileLength / (frameSize * frameRate));
 32             return durationInSeconds;
 33 
 34         }catch (Exception e){
 35             e.printStackTrace();
 36             return 0f;
 37         }
 38 
 39     }
 40 
 41     /**
 42      * 获取mp3语音文件播放时长(秒) mp3
 43      * @param filePath
 44      * @return
 45      */
 46     public static Float getMp3Duration(String filePath){
 47 
 48         try {
 49             File mp3File = new File(filePath);
 50             MP3File f = (MP3File) AudioFileIO.read(mp3File);
 51             MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
 52             return Float.parseFloat(audioHeader.getTrackLength()+"");
 53         } catch(Exception e) {
 54             e.printStackTrace();
 55             return 0f;
 56         }
 57     }
 58 
 59 
 60     /**
 61      * 获取mp3语音文件播放时长(秒)
 62      * @param mp3File
 63      * @return
 64      */
 65     public static Float getMp3Duration(File mp3File){
 66 
 67         try {
 68             //File mp3File = new File(filePath);
 69             MP3File f = (MP3File) AudioFileIO.read(mp3File);
 70             MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
 71             return Float.parseFloat(audioHeader.getTrackLength()+"");
 72         } catch(Exception e) {
 73             e.printStackTrace();
 74             return 0f;
 75         }
 76     }
 77 
 78 
 79     /**
 80      * 得到pcm文件的毫秒数
 81      *
 82      * pcm文件音频时长计算
 83      * 同图像bmp文件一样,pcm文件保存的是未压缩的音频信息。 16bits 编码是指,每次采样的音频信息用2个字节保存。可以对比下bmp文件用分别用2个字节保存RGB颜色的信息。 16000采样率 是指 1秒钟采样 16000次。常见的音频是44100HZ,即一秒采样44100次。 单声道: 只有一个声道。
 84      *
 85      * 根据这些信息,我们可以计算: 1秒的16000采样率音频文件大小是 2*16000 = 32000字节 ,约为32K 1秒的8000采样率音频文件大小是 2*8000 = 16000字节 ,约为 16K
 86      *
 87      * 如果已知录音时长,可以根据文件的大小计算采样率是否正常。
 88      * @param filePath
 89      * @return
 90      */
 91     public static long getPCMDurationMilliSecond(String filePath) {
 92         File file = new File(filePath);
 93 
 94         //得到多少秒
 95         long second = file.length() / 32000 ;
 96 
 97         long milliSecond = Math.round((file.length() % 32000)   / 32000.0  * 1000 ) ;
 98 
 99         return second * 1000 + milliSecond;
100     }
101 
102 
103 
104 
105 }
 1 package com.puxinwangxiao.mts.util;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.DataInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.InputStream;
 8 import java.net.HttpURLConnection;
 9 import java.net.MalformedURLException;
10 import java.net.URL;
11 import java.net.UnknownHostException;
12 
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15 
16 /**
17  * 文件处理
18  */
19 public class Image2Binary
20 {
21     private static Logger log = LoggerFactory.getLogger(Image2Binary.class);
22 
23     public static byte[] toByteArray(InputStream in) throws IOException {
24 
25         ByteArrayOutputStream out=new ByteArrayOutputStream();
26         byte[] buffer=new byte[1024*4];
27         int n=0;
28         while ( (n=in.read(buffer)) !=-1) {
29             out.write(buffer,0,n);
30         }
31         return out.toByteArray();
32     }
33 
34 
35     /**
36      * @throws IOException
37      * @throws MalformedURLException
38      * 网络文件转换为本地文件
39      * @Title: toByteArray
40      * @param @param url
41      * @param @return
42      * @param @throws IOException    设定文件
43      * @return byte[]    返回类型
44      * @throws
45      */
46     public static void toBDFile(String urlStr, String bdUrl) throws IOException,UnknownHostException{
47         URL url = new URL(urlStr);
48         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
49         DataInputStream in = new DataInputStream(conn.getInputStream());
50         byte[] data=toByteArray(in);
51         in.close();
52         FileOutputStream out=new FileOutputStream(bdUrl);
53         out.write(data);
54         out.close();
55     }
56 
57 
58 
59 }