1、接到需求需要后台再文件上传中读取视频时长
- 技术:springBoot fasdf文件服务器
引入音视频解析工具依赖
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-all-deps</artifactId>
<version>2.5.1</version>
</dependency>
/**
* 普通文件上传
*
* @return
*/
public Result uploadFile(MultipartFile file, String source, String resultType) {
String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String relative_path = today + "/";
String path = filePath + "/" + relative_path;
if (file.isEmpty()) {
return new Result(500, "文件为空!");
}
//文件名
String fileName = file.getOriginalFilename();
// 后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//新文件名
String uuidName = UUID.randomUUID().toString().replace("-", "");
String newfileName = uuidName + suffixName;
FileEntity entity = new FileEntity();
File orginFile = new File(path + newfileName);
try {
if (!orginFile.getParentFile().exists()) {
orginFile.getParentFile().mkdirs();
}
file.transferTo(orginFile);
} catch (IOException e) {
log.info(e.getMessage(), e);
}
entity.setDuration(this.ReadVideoTime(path + newfileName));
entity.setFileName(newfileName);
entity.setOrgName(fileName);
entity.setFilePath(relative_path + newfileName);
entity.setSource(source);
entity.setSize(file.getSize());
entity.setSuffix(suffixName);
baseMapper.insert(entity);
VO vo = new VO();
vo.setName(fileName);
vo.setSize(file.getSize());
vo.setDuration(entity.getDuration());
vo.setSuffix(suffixName);
vo.setOrgName(fileName);
if ("name".equals(resultType)) {
vo.setResult(uuidName);
} else {
vo.setResult(relative_path + newfileName);
}
return Result.success(vo);
}
方法
public String ReadVideoTime(String FileUrl) {
File source = new File(FileUrl);
String length = "";
long ls = 0L;
try {
MultimediaObject instance = new MultimediaObject(source);
MultimediaInfo result = instance.getInfo();
ls = result.getDuration();
} catch (Exception e) {
log.info("获取视频时长失败,{}", e.getMessage());
return length;
}
return getDurationDetails(ls);
}
public static String getDurationDetails(long ms) {
int ss = 1000;
int mi = ss * 60;
int hh = mi * 60;
int dd = hh * 24;
long day = ms / dd;
long hour = (ms - day * dd) / hh;
long minute = (ms - day * dd - hour * hh) / mi;
long second = (ms - day * dd - hour * hh - minute * mi) / ss;
//小时
String strHour = hour < 10 ? "0" + hour : "" + hour;
//分钟
String strMinute = minute < 10 ? "0" + minute : "" + minute;
//秒
String strSecond = second < 10 ? "0" + second : "" + second;
if (strHour.equals("00")) {
return strMinute + ":" + strSecond;
} else {
return strHour + ":" + strMinute + ":" + strSecond;
}
}