본문 바로가기
기타

비디오 태그로 영상 랜덤선택 재생 - HLS

by zgabriel 2025. 5. 13.
728x90

 

비디오 태그를 사용해서 주어진 주소 중 랜덤하게 선택해서 영상을 재생해주는 소스이다.

 

동영상의 HLS 방식을 사용했다. 

 

<video id="videoPlayer" width="700" autoplay muted playsinline ></video>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
  const videoFiles = [
    "영상1.mp4/playlist.m3u8","영상2.mp4/playlist.m3u8",
  ];

  const video = document.getElementById("videoPlayer");

  // 랜덤 인덱스 선택
  const randomIndex = Math.floor(Math.random() * videoFiles.length);
  const selectedSource = videoFiles[randomIndex];

  let hls;

  function playVideo(source) {
    if (hls) hls.destroy();

    if (Hls.isSupported()) {
      hls = new Hls();
      hls.loadSource(source);
      hls.attachMedia(video);
      hls.on(Hls.Events.MANIFEST_PARSED, () => {
        video.muted = true;
        video.play();
      });
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = source;
      video.muted = true;
      video.addEventListener('loadedmetadata', () => video.play());
    } else {
      console.error("HLS not supported in this browser.");
    }
  }

  // 한 번만 재생, ended 이벤트는 생략하거나 UI 제어용으로 사용
  playVideo(selectedSource);
</script>