203859-1729600739c249

Java获取上传音视频文件的时长

导入依赖

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

<!-- mp4文件支持(如语音时长)-->
<dependency>
<groupId>com.googlecode.mp4parser</groupId>
<artifactId>isoparser</artifactId>
<version>1.1.22</version>
</dependency>

工具类代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.File;

public class AudioUtil {


/**
* 获取语音文件播放时长(秒) 支持wav 格式
* @param filePath
* @return
*/
public static Float getDuration(String filePath){
try{

File destFile = new File(filePath);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(destFile);
AudioFormat format = audioInputStream.getFormat();
long audioFileLength = destFile.length();
int frameSize = format.getFrameSize();
float frameRate = format.getFrameRate();
float durationInSeconds = (audioFileLength / (frameSize * frameRate));
return durationInSeconds;

}catch (Exception e){
e.printStackTrace();
return 0f;
}

}

/**
* 获取mp3语音文件播放时长(秒) mp3
* @param filePath
* @return
*/
public static Float getMp3Duration(String filePath){

try {
File mp3File = new File(filePath);
MP3File f = (MP3File) AudioFileIO.read(mp3File);
MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
return Float.parseFloat(audioHeader.getTrackLength()+"");
} catch(Exception e) {
e.printStackTrace();
return 0f;
}
}


/**
* 获取mp3语音文件播放时长(秒)
* @param mp3File
* @return
*/
public static Float getMp3Duration(File mp3File){

try {
//File mp3File = new File(filePath);
MP3File f = (MP3File) AudioFileIO.read(mp3File);
MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
return Float.parseFloat(audioHeader.getTrackLength()+"");
} catch(Exception e) {
e.printStackTrace();
return 0f;
}
}


/**
* 得到pcm文件的毫秒数
*
* pcm文件音频时长计算
* 同图像bmp文件一样,pcm文件保存的是未压缩的音频信息。 16bits 编码是指,每次采样的音频信息用2个字节保存。可以对比下bmp文件用分别用2个字节保存RGB颜色的信息。 16000采样率 是指 1秒钟采样 16000次。常见的音频是44100HZ,即一秒采样44100次。 单声道: 只有一个声道。
*
* 根据这些信息,我们可以计算: 1秒的16000采样率音频文件大小是 2*16000 = 32000字节 ,约为32K 1秒的8000采样率音频文件大小是 2*8000 = 16000字节 ,约为 16K
*
* 如果已知录音时长,可以根据文件的大小计算采样率是否正常。
* @param filePath
* @return
*/
public static long getPCMDurationMilliSecond(String filePath) {
File file = new File(filePath);

//得到多少秒
long second = file.length() / 32000 ;

long milliSecond = Math.round((file.length() % 32000) / 32000.0 * 1000 ) ;

return second * 1000 + milliSecond;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* 文件处理
*/
public class Image2Binary
{
private static Logger log = LoggerFactory.getLogger(Image2Binary.class);

public static byte[] toByteArray(InputStream in) throws IOException {

ByteArrayOutputStream out=new ByteArrayOutputStream();
byte[] buffer=new byte[1024*4];
int n=0;
while ( (n=in.read(buffer)) !=-1) {
out.write(buffer,0,n);
}
return out.toByteArray();
}


/**
* @throws IOException
* @throws MalformedURLException
* 网络文件转换为本地文件
* @Title: toByteArray
* @param @param url
* @param @return
* @param @throws IOException 设定文件
* @return byte[] 返回类型
* @throws
*/
public static void toBDFile(String urlStr, String bdUrl) throws IOException,UnknownHostException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
DataInputStream in = new DataInputStream(conn.getInputStream());
byte[] data=toByteArray(in);
in.close();
FileOutputStream out=new FileOutputStream(bdUrl);
out.write(data);
out.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import com.coremedia.iso.IsoFile;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;


public class VideoUtil {


/**
* 获取视频文件的播放长度(mp4、mov格式)
* @param videoPath
* @return 单位为毫秒
*/
public static long getMp4Duration(String videoPath) throws IOException {
IsoFile isoFile = new IsoFile(videoPath);
long lengthInSeconds =
isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
return lengthInSeconds;
}


/**
* 得到语音或视频文件时长,单位秒
* @param filePath
* @return
* @throws IOException
*/
public static long getDuration(String filePath) throws IOException {
String format = getVideoFormat(filePath);
long result = 0;
if("wav".equals(format)){
result = AudioUtil.getDuration(filePath).intValue();
}else if("mp3".equals(format)){
result = AudioUtil.getMp3Duration(filePath).intValue();
}else if("m4a".equals(format)) {
result = VideoUtil.getMp4Duration(filePath);
}else if("mov".equals(format)){
result = VideoUtil.getMp4Duration(filePath);
}else if("mp4".equals(format)){
result = VideoUtil.getMp4Duration(filePath);
}
return result;
}

/**
* 得到语音或视频文件时长,单位秒
* @param filePath
* @return
* @throws IOException
*/
public static long getDuration(String filePath,String format) throws IOException {
long result = 0;
if("wav".equals(format)){
result = AudioUtil.getDuration(filePath).intValue();
}else if("mp3".equals(format)){
result = AudioUtil.getMp3Duration(filePath).intValue();
}else if("m4a".equals(format)) {
result = VideoUtil.getMp4Duration(filePath);
}else if("mov".equals(format)){
result = VideoUtil.getMp4Duration(filePath);
}else if("mp4".equals(format)){
result = VideoUtil.getMp4Duration(filePath);
}

return result;
}


/**
* 得到文件格式
* @param path
* @return
*/
public static String getVideoFormat(String path){
return path.toLowerCase().substring(path.toLowerCase().lastIndexOf(".") + 1);
}

public static String getFileByUrl(String url) throws UnknownHostException, IOException{
File tmpFile = File.createTempFile("temp", url.substring(url.lastIndexOf(".")));//创建临时文件
Image2Binary.toBDFile(url, tmpFile.getCanonicalPath());
return tmpFile.getCanonicalPath();
}
}

代码测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@SpringBootTest
class FileDurationDemoApplicationTests {

@Test
void netFile() {
//网络文件
String path = "https://m704.music.126.net/20241117101848/98c3b23cae7a8ccd722940457fceecb3/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/44782833085/a2bc/ca8d/94cd/4dcab809365bf082bcc79a6e07f90266.m4a" ;
long result = 0;
try {
String tmpPath = VideoUtil.getFileByUrl(path);
result = VideoUtil.getDuration(tmpPath);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
}

@Test
void localFile(){
//本地文件
String path = "D:\\素材\\视频\\avi.avi" ;
long result = 0;
try {
result = VideoUtil.getDuration(path);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
}

}