2 回答
TA贡献1811条经验 获得超6个赞
范围包括开始到结束。不是起始长度
例如:
Content-range: bytes 0-0/31491166
返回 1 个字节(从字节零到字节零)
您的代码不起作用,因为浏览器正在等待一个从未发送过的字节。
TA贡献1784条经验 获得超7个赞
使用下面的代码片段。它在所有浏览器Safari、Firefox 和 Chrome上运行和测试。
protected byte[] prepareContent(final HttpHeaders headers, byte[] media,
String range) throws IOException {
long rangeStart = 0;
long rangeEnd;
long fileSize = media.length;
String[] ranges = range.split("-");
rangeStart = Long.parseLong(ranges[0].substring(6));
if (ranges.length > 1) {
rangeEnd = Long.parseLong(ranges[1]);
} else {
rangeEnd = fileSize - 1;
}
if (fileSize < rangeEnd) {
rangeEnd = fileSize - 1;
}
String contentLength = String.valueOf((rangeEnd - rangeStart) + 1);
headers.add("Content-Length", contentLength);
headers.add("Content-Range", "bytes " + rangeStart + "-" + rangeEnd + "/" + fileSize);
headers.add("Content-Type", "video/mp4");
headers.add("Accept-Ranges","bytes");
return readByteRange(media, rangeStart, rangeEnd);
}
private byte[] readByteRange(byte[] media, long start, long end) throws IOException {
try (InputStream inputStream = new ByteArrayInputStream(media);
ByteArrayOutputStream bufferedOutputStream = new ByteArrayOutputStream()) {
int nRead;
while ((nRead = inputStream.read(media, 0, media.length)) != -1) {
bufferedOutputStream.write(media, 0, nRead);
}
bufferedOutputStream.flush();
byte[] result = new byte[(int) (end - start) + 1];
System.arraycopy(bufferedOutputStream.toByteArray(), (int) start, result, 0, result.length);
return result;
}
}
添加回答
举报