Javascript

🎲 embed youtube 여러개 영상 이어서 + 랜덤하게 재생하기 (embed youtube playlist random play)

728x90
클라이언트 요청사항
- 여러 개의 유튜브 영상이 랜덤한 순서로 연이어서 자동재생 되면 좋겠어요.

 

 

 

✅ 구현 화면

 

3개의 각각 다른 영상이 랜덤한 순서로 연이어 재생된다.

손현주 아저씨 - 마시는 화이바 - 여성등장 영상

 

이렇게 세개의 영상이 랜덤한 규칙성을 가지고 재생된다.

이때, 한차례 영상이 다 재생되고 처음으로 돌아올때 같은 영상이 또 재생되지 않도록 한다.

 

👩🏻‍💻 구현 코드

<!DOCTYPE html>
<html>
  <head>
    <title>YouTube Playlist Randomizer</title>
  </head>
  <body>
    <div id="player"></div>
    <script>
      // YouTube IFrame API를 비동기로 로드
      var tag = document.createElement("script");
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName("script")[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      var player;
      var playlist = ["41osFpTtc_Q", "Iu2uB6Xl-PE", "rrYnzttx1Rw"]; // 여기에 플레이리스트 비디오 ID 추가
      var currentPlaylist = shuffleArray(playlist.slice()); // 초기 재생 목록을 셔플
      var playedVideos = [];
      var lastPlayedVideo = null;

      // 배열을 무작위로 섞는 함수
      function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
          var j = Math.floor(Math.random() * (i + 1));
          [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
      }

      // API가 준비되었을 때
      function onYouTubeIframeAPIReady() {
        player = new YT.Player("player", {
          height: "390",
          width: "640",
          videoId: getNextVideoId(),
          events: {
            onReady: onPlayerReady,
            onStateChange: onPlayerStateChange,
          },
        });
      }

      // 플레이어가 준비되었을 때
      function onPlayerReady(event) {
        event.target.playVideo();
      }

      // 플레이어 상태가 변경되었을 때
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.ENDED) {
          player.loadVideoById(getNextVideoId());
        }
      }

      // 다음 비디오 ID를 반환하는 함수
      function getNextVideoId() {
        if (currentPlaylist.length === 0) {
          currentPlaylist = shuffleArray(playedVideos.slice());
          playedVideos = [];
        }
        var nextVideoId = currentPlaylist.shift();

        // 마지막으로 재생된 비디오와 같은 경우 다음 비디오를 가져옴
        if (nextVideoId === lastPlayedVideo && currentPlaylist.length > 0) {
          currentPlaylist.push(nextVideoId);
          nextVideoId = currentPlaylist.shift();
        }

        playedVideos.push(nextVideoId);
        lastPlayedVideo = nextVideoId;

        return nextVideoId;
      }
    </script>
  </body>
</html>

 

728x90
반응형