使用mdn Mediasource和Java后端创建Streaming Player。
客户代码。
myMediaSource.addEventListener("sourceopen", () => {
var videoSourceBuffer = myMediaSource
.addSourceBuffer('video/webm; codecs="vorbis,vp8"');
this.range = this.initialRange * this.rangeCounter;
this.loadVideoChunks(videoSourceBuffer, `0-${this.range}`, myMediaSource);
this.updateEndEvent(videoSourceBuffer, myMediaSource, video, url);
});
myMediaSource.addEventListener("error", (e) => {
console.log(e);
});
}
updateEndEvent(videoSourceBuffer, myMediaSource, video, url) {
var self = this;
videoSourceBuffer.addEventListener("updateend", (e) => {
if (!videoSourceBuffer.updating && myMediaSource.readyState === "open" && self.rangeCounter == -1) {
myMediaSource.endOfStream();
}
if (self.rangeCounter < 5) {
// videoSourceBuffer.timestampOffset = self.duration;
// const delta = myMediaSource.duration;
// self.duration = self.duration + delta;
self.loadVideoChunks(videoSourceBuffer, `${self.range}-${self.initialRange * self.rangeCounter}`, myMediaSource);
self.range = self.initialRange * self.rangeCounter;
}
});
}
loadVideoChunks(videoSourceBuffer: any, range, myMediaSource) {
var self = this;
this.$http({
method: "GET",
transformRequest: angular.identity,enter code here
headers: {"Content-Type": undefined},
url: `stream-url/${range}`,
responseType: "arraybuffer"
}).then((response: any ) => {
const result = new Uint8Array(response.data);
if (!videoSourceBuffer.updating) {
videoSourceBuffer.appendBuffer(result);
}
if (response.headers('endOfStream') == -1) {
this.rangeCounter = -1;
} else {
this.rangeCounter += 1;
}
});
});
Java代码:
String[] rangeArray = range.split("-");
long startOffset = Long.parseLong(rangeArray[0]);
long endOffset = Long.parseLong(rangeArray[1]);
byte buffer[] = new byte[(int)endOffset];
File FILE1 = new File("C:\\videos\\b.webm");
URL url = FILE1.toURI().toURL();
File file = new File(url.getFile());
InputStream inputStream = new FileInputStream(file);
inputStream.skip(startOffset);
int read = inputStream.read(buffer);
return Response.ok(buffer)
.header(com.varian.frameworks.util.HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS,
"endOfStream,Content-Length,Content-Type,Accept-Ranges,Content-Range")
.header("endOfStream", read)
.header("Content-Length",file.length())
.header("Content-Type","video/webm")
.header("Content-Range","bytes "+rangeArray[0] +"-" +rangeArray[1] + "/" +file.length())
.header("Accept-Ranges","bytes")
.status(206).build();
视频有效,但在最后一块中断。 无法在'SourceBuffer'上执行'appendBuffer':HTMLMediaElement.error属性不为null。 可能是我做错了 请帮助我。