Java获取视频的大小、时长

时间:2023-01-03 19:45:51

前端上传视频之后,根据上传的视频文件获取视频的大小和时长

1、获取视频时长

private String ReadVideoTime(File source) {
Encoder encoder = new Encoder();
String length = "";
try {
MultimediaInfo m = encoder.getInfo(source);
long ls = m.getDuration()/1000;
int hour = (int) (ls/3600);
int minute = (int) (ls%3600)/60;
int second = (int) (ls-hour*3600-minute*60);
length = hour+"'"+minute+"''"+second+"'''";
} catch (Exception e) {
e.printStackTrace();
}
return length;
}

 

2、获取视频大小

/**
* 获取视频大小
* @param source
* @return
*/
private String ReadVideoSize(File source) {
FileChannel fc= null;
String size = "";
try {
@SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(source);
fc= fis.getChannel();
BigDecimal fileSize = new BigDecimal(fc.size());
size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null!=fc){
try{
fc.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
return size;
}

***获取视频大小的时候,由于用到了流,使用完之后一定要及时的关闭流,避免无法删除视频文件***