目标
最近项目中需要对上传的本地视频和从其他服务器拷贝的视频进行校验功能,校验主要包括视频的时长,大小,格式等信息,那么如何获取这些信息呢?
思路
本地视频,从过文件流读取,再通过FFMpeg.exe获取到相关视频信息;
网络视频,通过http下载到本地临时文件,在通过上述本地视频方法获取相关信息
过程
1.下载ffmpeg.exe,下载地址自行百度;
2.将ffmpeg.exe的绝对路径,拷贝放进如下代码中;
3.详细代码实现过程如下
public void testVideo(String path) {
File source = new File(path);
FFMPEGLocator locator = new FFMPEGLocator() {
@Override
protected String getFFMPEGExecutablePath() {
return "D:\\DevelopTools\\ffmpeg-20180602-5ee2030-win64-static\\bin\\ffmpeg.exe";
}
};
Encoder encoder = new Encoder(locator);
FileChannel fc = null;
String size = "";
try {
it.sauronsoftware.jave.MultimediaInfo m = encoder.getInfo(source);
long ls = m.getDuration();
System.out.println("此视频时长为:" + ls / 60000 + "分" + (ls) / 1000 + "秒!");
System.out.println("此视频高度为:" + m.getVideo().getSize().getHeight());
System.out.println("此视频宽度为:" + m.getVideo().getSize().getWidth());
System.out.println("此视频格式为:" + m.getFormat());
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";
System.out.println("此视频大小为" + size);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fc) {
try {
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public File inputstreamtofile(InputStream ins, String ext) throws IOException{
File f = new File("d:\\Temp");
File file = File.createTempFile("temp", ext, f);
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return file;
}
public InputStream getImgFromUrl(String url) throws IOException{
URL myUrl = new URL(url);
HttpURLConnection con = (HttpURLConnection) myUrl.openConnection();
con.setConnectTimeout(5*1000);
InputStream is = con.getInputStream();
return is;
}
/**
* 远程文件(视频/图片)存储
* @throws IOException
*/
@Test
public void insertBlobRemote() throws Exception {
String url = "http://10.50.13.68:18080/images/luping.mp4";
String ext = url.substring(url.lastIndexOf("."));
InputStream inputStream = getImgFromUrl(url);
File file = inputstreamtofile(inputStream, ext);
FileInputStream fis = new FileInputStream(file);
String path = file.getPath();
System.out.println("-------临时文件路径----------"+path);
testVideo(path);
fis.close();
}
4.运行结果如下图
总结
1.需要下载ffmpeg.exe,如果应用部署到Linux上,也需将此文件上传上去,并配置正确的文件路径;
2.网络视频需要下载到本地再进行处理,如果视频较大的话,比较耗时;
3.网络视频下载下来,如果怕占用空间的话,获取到视频相关信息后需要及时删掉,即退出时执行file.deleteOnExit();