Fork me on GitHub

MediaSource 音视频合并

引自Javascrit中使用MediaSource播放加密视频

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<html>
<head>
<title>MSE Demo</title>
<style>
video {
max-width: 100%;
}
</style>

<script type="text/javascript">

var audioFragments = [
"media/audio/init.mp4",
"media/audio/seg-1.mp4",
"media/audio/seg-2.mp4",
"media/audio/seg-3.mp4",
"media/audio/seg-4.mp4",
"media/audio/seg-5.mp4",
"media/audio/seg-6.mp4",
"media/audio/seg-7.mp4",
];
var videoFragments = [
"media/video/init.mp4",
"media/video/seg-1.mp4",
"media/video/seg-2.mp4",
"media/video/seg-3.mp4",
"media/video/seg-4.mp4",
"media/video/seg-5.mp4",
"media/video/seg-6.mp4",
"media/video/seg-7.mp4",
];

function MSELoadTrack(fragments, type, mediaSource, name) {
return new Promise(function(resolve, reject) {
var sourceBuffer;
var curFragment = 0;

function addNextFragment() {
if (mediaSource.readyState == "closed") {
return;
}
if (curFragment >= fragments.length) {
resolve();
return;
}

var fragmentFile = fragments[curFragment++];

var req = new XMLHttpRequest();
req.open("GET", fragmentFile);
req.responseType = "arraybuffer";

req.addEventListener("load", function() {
sourceBuffer.appendBuffer(new Uint8Array(req.response));
});

req.addEventListener("error", function(){reject();});
req.addEventListener("abort", function(){reject();});

req.send(null);
}

sourceBuffer = mediaSource.addSourceBuffer(type);
sourceBuffer.addEventListener("updateend", addNextFragment);
addNextFragment();

});
}

</script>

</head>
<body>
<h1>Media Source Extensions Demo</h1>

<video id="v" controls preload="auto"></video>

<script>

function Load() {

var video = document.getElementById("v");

const audioContentType = 'audio/mp4; codecs="mp4a.40.2"'; // AAC-LC
const videoContentType = 'video/mp4; codecs="avc1.64001F"'; // High profile level 3.1

var ms = new MediaSource();
video.src = URL.createObjectURL(ms);

var SourceOpen = function () {
ms.removeEventListener("sourceopen", SourceOpen);

Promise.all([MSELoadTrack(videoFragments, videoContentType, ms, "video"), MSELoadTrack(audioFragments, audioContentType, ms, "audio")]).then(function(){ms.endOfStream();});

}

ms.addEventListener("sourceopen", SourceOpen);
video.addEventListener("canplay", function(){video.play();});
}

Load();

</script>
</body>
</html>
-------------感谢您的阅读 有问题请留言(或mailto:frostbelt@sina.cn)-------------