啊哈,反正就是要播放hls的视频流,然后要自定义播放按钮啥啥啥的。┏ (゜ω゜)=☞
感觉需求相对简单一点,所以不想用video.js
,但是video标签是不能直接放hls格式的,所以需要用 hls.js
直接上代码吧~
tsx文件
import Hls from 'hls.js';
const videoRef = useRef<HTMLVideoElement>(null);
const setHlsUrl = (videoDOM: any, hlsUrl: string) => {
const hls = new Hls();
hls.loadSource(hlsUrl);
hls.attachMedia(videoDOM);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
videoDOM.play();
});
hls.on(Hls.Events.ERROR, (event, data) => {
if (data.fatal) {
if (
data.type === Hls.ErrorTypes.NETWORK_ERROR ||
(data.response && data.response.code === 404)
) {
console.log('视频404');
}
}
});
};
const init = () => {
if (videoRef.current && isHls && url) {
const videoDOM = videoRef.current;
// 支持m3u8,直接使用video播放
if (videoDOM.canPlayType('application/vnd.apple.mpegurl')) {
videoDOM.src = url;
videoDOM.addEventListener('canplay', () => {
videoDOM.play();
});
videoDOM.addEventListener('error', () => {
console.log('视频播放错误');
});
} else if (Hls.isSupported()) {
...
}
}
};
useEffect(() => {
init();
}, [videoRef.current]);
return (
<div className="jsx-video-player">
<video
ref={videoRef}
muted
title={name || '视频'}
width={468}
height={350}
loop
autoPlay={autoPlay !== undefined ? autoPlay : !pic}
controls={status}
poster={pic}
src={isHls ? undefined : url}
disablePictureInPicture
{...props}
>
你的浏览器不支持 <code>video</code> 标签.
</video>
{!autoPlay && !status ? (
<img
className="jsx-video-player_play"
onClick={() => {
setHlsUrl();
}}
alt="播放"
src={play}
/>
) : null}
</div>
);
};
export default VideoPlayer;
Scss文件
.jsx-video-player {
// 全屏播放自适应屏幕
video {
object-fit: fill;
}
// 全屏按钮
video::-webkit-media-controls-fullscreen-button {
display: none;
}
// 播放按钮
video::-webkit-media-controls-play-button {
display: none;
}
// 进度条
video::-webkit-media-controls-timeline {
display: none;
}
// 观看的当前时间
video::-webkit-media-controls-current-time-display {
display: none;
}
// 剩余时间
video::-webkit-media-controls-time-remaining-display {
display: none;
}
// 音量按钮
video::-webkit-media-controls-mute-button {
display: none;
}
video::-webkit-media-controls-toggle-closed-captions-button {
display: none;
}
// 音量的控制条
video::-webkit-media-controls-volume-slider {
display: none;
}
// 所有控件
video::-webkit-media-controls-enclosure {
display: none;
}
.jsx-video-player_play {
cursor: pointer;
position: absolute;
top: 40%;
left: 42%;
}
}
相关资料: