随着国内带宽降费提速日益普及,与此同时移动通信技术也进一步提升,视频,直播这一类业务需求都离不开推流这一核心技术点。最近尝试了一次SpringMVC的H264流响应方法,SpringMVC提供了一个ResourceRegion对象,类比于RandomAccessFile,其抽象了资源的随机位置响应方法,所以只要用ResourceRegion响应,即可完成一个简单的H264流响应。

@GetMapping("/play/{name}")
public ResponseEntity<ResourceRegion> play(@PathVariable("name") String name,@RequestHeader HttpHeaders httpHeaders) throws IOException {
UrlResource video =new UrlResource("file:"+ARCHIVE_DIR_STR+"/"+name+".mp4");
ResourceRegion resourceRegion = resourceRegion(video, httpHeaders);
return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
.contentType(MediaTypeFactory
.getMediaType("video/mp4")
.orElse(MediaType.APPLICATION_OCTET_STREAM))
.body(resourceRegion);
}
private ResourceRegion resourceRegion(UrlResource video, HttpHeaders headers) throws IOException {
long contentLength = video.contentLength();
HttpRange range = headers.getRange().get(0);
if (range != null) {
long start = range.getRangeStart(contentLength);
long end = range.getRangeEnd(contentLength);
long rangeLength = Math.min(1 * 1024 * 1024, end - start + 1);
return new ResourceRegion(video, start, rangeLength);
} else {
long rangeLength = Math.min(1 * 1024 * 1024, contentLength);
return new ResourceRegion(video, 0, rangeLength);
}
}

现代浏览器普遍都支持了video的tag,所以只需要在video的tag里面设置source为SpringMVC的流响应接口即可完成通过浏览器源生播放器进行播放,当然要想实现如倍速、快捷键等更多功能也可以通过其他开源播放器项目进行定制。

<html lang="en">
<head>
<meta charset="UTF-8">
<title>PlayPage</title>
</head>
<body>
<video autoplay="autoplay" controls>
<source src="/play/name" type="video/mp4">
</video>
</body>
</html>