# 13.hls.js实战
hls.js轻量级, 扩展性高, 比较适合自定义移动端直播UI界面
# 效果

# 相关代码
# index.html
hls.js好处在于它的轻量,可以在没有冗余的情况下自定义播放器的样式,以下是冗长的示例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>hls.js演示</title>
<script src="./hls.js" type="text/javascript"></script>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="player pause">
<video id="video"></video>
<em class="btn"></em>
<span class="state">正在直播</span>
</div>
<script src="./index.js" type="text/javascript"></script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# index.js
var Hls = window.Hls
var video = document.getElementById('video');
var btn = document.querySelector('.btn')
var player = document.querySelector('.player')
var videoSrc = 'http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8';
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(videoSrc);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function() {
video.play();
});
}
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = videoSrc;
video.addEventListener('loadedmetadata', function() {
video.play();
});
}
// 实现播放器的暂停和播放控制, 以及按钮的切换状态
btn.addEventListener('click', function() {
// 判断video 的状态
if(video.paused) {
video.play()
}else {
video.pause()
}
})
video.addEventListener('click',()=>{
if(video.paused) {
video.play()
}else {
video.pause()
}
})
// 监听 video 的状态
video.addEventListener('play', () => {
player.className = 'player'
})
video.addEventListener('pause',() => {
player.className = 'player pause'
})
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
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
# index.css
.player {
width: 400px;
height: 200px;
position: relative;
}
.player video {
width: 100%;
height: 100%;
}
.player .btn {
display: none;
width: 40px;
height: 40px;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
padding: 15px;
background: rgba(255, 255, 255, 0.5);
line-height: 40px;
}
.player .btn:hover {
background: rgba(255,255,255,0.7);
}
.player .btn::before {
border: 20px solid #ddd;
border-top-color: transparent;
border-right-color: transparent;
border-bottom-color: transparent;
content: '';
display: block;
margin-left: 14px;
width: 0;
height: 0;
}
.player .btn::before:hover {
border-left-color: #fff;
}
.player.pause .btn {
display: block;
}
.player .state {
position: absolute;
bottom: 20px;
left: 30px;
font-size: 14px;
color: red;
}
.player.pause .state {
display: none;
}
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
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