// 视频组件 import muxjs from 'mux.js';
export default class VideoPlayer { constructor(segments, videoElement) {
console.log("🚀 ~ 🚀🚀~ VideoPlayer ~ 🚀🚀~ segments, videoElement:", segments, videoElement)
this.segments = segments || ['/dev-api/video', '/dev-api/video2'];
this.videoElement = videoElement || document.getElementById('tsVideo');
console.log("🚀 ~ 🚀🚀~ VideoPlayer ~ 🚀🚀~ videoElement:", this.videoElement)
this.mediaSource = new MediaSource();
this.transmuxer = new muxjs.mp4.Transmuxer();
this.sourceBuffer = null;
this.init();
}
init() { this.videoElement.src = URL.createObjectURL(this.mediaSource); this.mediaSource.addEventListener('sourceopen', () => this.appendFirstSegment()); }
appendFirstSegment() { if (this.segments.length == 0) { return; }
URL.revokeObjectURL(this.videoElement.src);
const mime = 'video/mp4; codecs="mp4a.40.2,avc1.64001f"';
this.sourceBuffer = this.mediaSource.addSourceBuffer(mime);
this.sourceBuffer.addEventListener('updateend', () => this.appendNextSegment());
this.transmuxer.on('data', (segment) => {
let data = new Uint8Array(segment.initSegment.byteLength + segment.data.byteLength);
data.set(segment.initSegment, 0);
data.set(segment.data, segment.initSegment.byteLength);
this.sourceBuffer.appendBuffer(data);
this.transmuxer.off('data');
});
fetch(this.segments.shift())
.then((response) => response.arrayBuffer())
.then((response) => {
this.transmuxer.push(new Uint8Array(response));
this.transmuxer.flush();
})
.catch((err) => console.error(err));
}
appendNextSegment() { this.transmuxer.on('data', (segment) => { this.sourceBuffer.appendBuffer(new Uint8Array(segment.data)); this.transmuxer.off('data'); });
if (this.segments.length == 0) {
this.mediaSource.endOfStream();
return;
}
fetch(this.segments.shift())
.then((response) => response.arrayBuffer())
.then((response) => {
this.transmuxer.push(new Uint8Array(response));
this.transmuxer.flush();
});
} }