java返回H5視訊流能夠在IOS中播放
在IOS中,H5頁面中,video標籤下,視訊源必須滿足range的要求,如果視訊比如快進或者後退,實際上是再次傳送了視訊源的請求只不過range的範圍不同。不說了,上程式碼:
public void returnVideo(String videoPath, String videoFileName, HttpServletRequest request,
HttpServletResponse response) throws IOException {
Path video = Paths.get(videoPath, videoFileName);
int length = (int) Files.size(video);
int start = 0;
int end = length - 1;
String range = request.getHeader("Range");
range = range == null ? "" : range;
Matcher matcher = RANGE_PATTERN.matcher(range);
if (matcher.matches()) {
String startGroup = matcher.group("start");
start = startGroup.isEmpty() ? start : Integer.valueOf(startGroup);
start = start < 0 ? 0 : start;
String endGroup = matcher.group("end");
end = endGroup.isEmpty() ? end : Integer.valueOf(endGroup);
end = end > length - 1 ? length - 1 : end;
}
int contentLength = end - start + 1;
response.reset();
response.setBufferSize(BUFFER_LENGTH);
response.setHeader("Content-Disposition", String.format("inline;filename=\"%s\"", videoFileName));
response.setHeader("Accept-Ranges", "bytes");
response.setDateHeader("Last-Modified", Files.getLastModifiedTime(video).toMillis());
response.setDateHeader("Expires", System.currentTimeMillis() + EXPIRE_TIME);
response.setContentType(Files.probeContentType(video));
response.setHeader("Content-Range", String.format("bytes %s-%s/%s", start, end, length));
response.setHeader("Content-Length", String.format("%s", contentLength));
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
int bytesRead;
int bytesLeft = contentLength;
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_LENGTH);
try (SeekableByteChannel input = Files.newByteChannel(video, StandardOpenOption.READ);
OutputStream output = response.getOutputStream()) {
input.position(start);
while ((bytesRead = input.read(buffer)) != -1 && bytesLeft > 0) {
buffer.clear();
output.write(buffer.array(), 0, bytesLeft < bytesRead ? bytesLeft : bytesRead);
bytesLeft -= bytesRead;
}
}
}