0%

视频url的处理

视频url的处理

  1. 从url中读取流
  2. 将流转化为文件
  3. 使用MultimediaInfo中的方法获取视频文件的信息
1
2
3
4
5
6
<!-- 添加依赖 -->
<dependency>
<groupId>it.sauronsoftware</groupId>
<artifactId>jave</artifactId>
<version>1.0.2</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
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.MultimediaInfo;

// 因为收到的是链接地址,所以需要先将链接转化为文件
/**
* 从链接地址读取流
*
* @param urlPath
* @return
*/
public static InputStream getIsFromUrl(String urlPath) {
HttpURLConnection conn = null;
try {
String urlStr = URLDecoder.decode(urlPath, "UTF-8");
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
return conn.getInputStream();
} catch (IOException ioe) {
logger.error("[Method-getIsFromUrl]exception:{}", ioe.getMessage());
}finally{
if (conn != null) {
conn.disconnect();
}
}
return null;
}

/**
* 将流读成文件
*
* @param ins
* @param file
* @throws IOException
*/
public static void inputStreamToFile(InputStream ins, File file) {
OutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
int a = 8192;
byte[] buffer = new byte[a];
while ((bytesRead = ins.read(buffer, 0, a)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException ioe) {
logger.error("[Method-inputStreamToFile]exception:{}", ioe.getMessage());
} finally {
try {
if (null != os) {
os.close();
}
} catch (IOException ioe) {
logger.error("[Method-inputStreamToFile]close-exception:{}", ioe.getMessage());
}
}
}

/**
* 获取网络文件,暂存为临时文件
*
* @param url
* @param tempPath 临时文件地址
* @return
* @throws UnknownHostException
* @throws IOException
*/
public static File getFileFromUrl(String url, String tempPath)
throws UnknownHostException, IOException {
//创建临时文件
File file = new File(tempPath);
File tmpFile = File.createTempFile("temp", ".tmp", file);
// 程序结束后删除(缓存delete命令,jvm停止时执行)
tmpFile.deleteOnExit();
logger.info("[getFileFromUrl]create file from url:{},path:{}",
url, file.getAbsolutePath());
InputStream is = getIsFromUrl(url);
if (null != is) {
inputStreamToFile(is, tmpFile);
}
return tmpFile;
}

/**
* 获取视频时长 单位秒
*/
public static Long getDuration(File file) throws EncoderException {
MultimediaInfo m = new Encoder().getInfo(file);
return m.getDuration() / 1000;
}

上述代码就是获取一个视频地址视频时长的全部内容。逻辑比较简单,先把链接地址读取成文件流,
然后用jave的方法获取其时长(单位是毫秒,因为业务需求将其计算转为秒)。