This repository was archived by the owner on Mar 13, 2025. It is now read-only.
forked from mingxinstar/react-hls
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathindex.tsx
More file actions
91 lines (77 loc) · 2.19 KB
/
index.tsx
File metadata and controls
91 lines (77 loc) · 2.19 KB
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
import React, { useEffect, RefObject } from 'react';
import Hls, { Config } from 'hls.js';
export interface HlsPlayerProps
extends React.VideoHTMLAttributes<HTMLVideoElement> {
hlsConfig?: Config;
playerRef: RefObject<HTMLVideoElement>;
src: string;
}
function ReactHlsPlayer({
hlsConfig,
playerRef = React.createRef<HTMLVideoElement>(),
src,
autoPlay,
...props
}: HlsPlayerProps) {
useEffect(() => {
let hls: Hls;
function _initPlayer() {
if (hls != null) {
hls.destroy();
}
const newHls = new Hls({
enableWorker: false,
...hlsConfig,
});
if (playerRef.current != null) {
newHls.attachMedia(playerRef.current);
}
newHls.on(Hls.Events.MEDIA_ATTACHED, () => {
newHls.loadSource(src);
newHls.on(Hls.Events.MANIFEST_PARSED, () => {
if (autoPlay) {
playerRef?.current
?.play()
.catch(() =>
console.log(
'Unable to autoplay prior to user interaction with the dom.'
)
);
}
});
});
newHls.on(Hls.Events.ERROR, function (event, data) {
if (data.fatal) {
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
newHls.startLoad();
break;
case Hls.ErrorTypes.MEDIA_ERROR:
newHls.recoverMediaError();
break;
default:
_initPlayer();
break;
}
}
});
hls = newHls;
}
// Check for Media Source support
if (typeof window !== 'undefined') {
Hls.isSupported() && _initPlayer();
}
return () => {
if (hls != null) {
hls.destroy();
}
};
}, [autoPlay, hlsConfig, playerRef, src]);
// If Media Source is supported, use HLS.js to play video
if (typeof window !== 'undefined') {
if (Hls.isSupported()) return <video ref={playerRef} {...props} />;
}
// Fallback to using a regular video player if HLS is supported by default in the user's browser
return <video ref={playerRef} src={src} autoPlay={autoPlay} {...props} />;
}
export default ReactHlsPlayer;