因为项目需要有空研究了一下 ffmpeg ,安装过程就不贴了,我的开发环境是linux ,大家自行百度就好!
废话不多说 直接上代码(ps:有错误的地方,望大神指正)
截取视频第一帧:(ffmpeg)
截取帧数是可调控的,大小也是可以调控的,在参数里都写了。自己看!
/**
* 获取视频第一帧
* @param video_path
* @return
*/
private static String processImg(String video_path) {
File file = new File(video_path);
String path = "";
if (!file.exists()) {
System.err.println("路径[" + video_path + "]对应的视频文件不存在!");
return path;
}
List<String> commands = new java.util.ArrayList<String>();
commands.add(PropertyUtil.getProperty("ffmpeg_path"));
commands.add("-i");
commands.add(video_path);
commands.add("-y");
commands.add("-f");
commands.add("image2");
commands.add("-ss");
commands.add("1");//这个参数是设置截取视频多少秒时的画面
commands.add("-t");
commands.add("0.001");
//commands.add("-s");
//commands.add("1920x1080");//宽X高
path = video_path.substring(0, video_path.lastIndexOf(".")).replaceFirst("vedio", "file") + ".jpg";
commands.add(path);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commands);
builder.start();
System.out.println("截取成功");
//休眠两秒,要不然上传图片的时候会找不到图片
Thread.sleep(2000);
String id = "";
File img = new File(path);
//清理文件
if (img.exists()) {
//上传截图
System.out.println("~~~~~~~~~~~~~~~~~ 上传视频第一帧, 删除图片 ~~~~~~~~~~~~~~~~~");
id = FileUtilByRest.uploadFile(img,UUIDUtil.createUUID() + ".jpg");
img.delete();
}
return id;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
获取视频时长:(jave jar包自行百度)
音频也通用
/**
* 获取视频文件时长
* @param music
* @return
* @throws BitstreamException
*/
private String getVideoTime(File music)throws IOException, BitstreamException {
System.out.println("~~~~~~~~~~~~~~~~ 开始获取视频时长 ~~~~~~~~~~~~~~~~~");
Encoder encoder = new Encoder();
try {
MultimediaInfo m = encoder.getInfo(music);
long ls = m.getDuration();
int time = (int) ls / 1000;
int ss = time % 60;
int mm = time / 60 % 60;
int hh = time / 60 / 60 % 24;
String result = "";
if(ss != 0){
String HH = hh == 0 ? "" : getTime(hh) + ":";
result = HH + getTime(mm) + ":" + getTime(ss);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "00:00";
}
/**
* 把时间转换成字符串
* @param time
* @return
*/
private String getTime(int time) {
if(time == 0){
return "00";
}else{
if(time <= 9 ){
return "0" + time;
}else{
return time + "";
}
}
}
获取视频大小:(nio)
/**
* 获取视频大小
* @param source
* @return
*/
private Long readVideoSize(File source) {
FileChannel fc= null;
Long size = 0L;
try {
@SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(source);
fc= fis.getChannel();
BigDecimal fileSize = new BigDecimal(fc.size());
size = Long.parseLong(fileSize.toString());
if (size > 0) {
size = Long.parseLong(fileSize.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null!=fc){
try{
fc.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
return size;
}