一次播放一个YouTube视频

时间:2018-11-29 20:02:26

标签: javascript youtube youtube-api

我将如何调整此代码,以便一次只能播放一个视频?进行设置,以便如果我单击其他视频,之前的视频会暂停吗?这是我一直在尝试做的事情,似乎无法弄清楚该怎么做。

这将如何完成?我要添加什么代码才能实现此功能?

代码

https://jsfiddle.net/d72Lp43v/293/

num(num(num(S,2),3),4) # S = [24, 48, 72, 96]

3 个答案:

答案 0 :(得分:2)

一次播放一个视频非常棘手,但很容易...

几天前,即使我在处理视频轮播时也遇到了同样的问题...最后,我现在有一个解决方案...首先,使用<iframe>标签嵌入youtube视频,然后在视频网址?html5=1&enablejsapi=1的末尾键入以下内容...然后将以下JavaScript代码直接包含在您的项目中,而无需对其进行任何编辑!

所需功能的JavaScript代码如下-

      <script>
    var ytplayerList;

    function onPlayerReady(e) {
        var video_data = e.target.getVideoData(),
            label = video_data.video_id+':'+video_data.title;
        e.target.ulabel = label;
        console.log(label + " is ready!");

    }
    function onPlayerError(e) {
        console.log('[onPlayerError]');
    }
    function onPlayerStateChange(e) {
        var label = e.target.ulabel;
        if (e["data"] == YT.PlayerState.PLAYING) {
            console.log({
                event: "youtube",
                action: "play:"+e.target.getPlaybackQuality(),
                label: label
            });
            //if one video is play then pause other
            pauseOthersYoutubes(e.target);
        }
        if (e["data"] == YT.PlayerState.PAUSED) {
            console.log({
                event: "youtube",
                action: "pause:"+e.target.getPlaybackQuality(),
                label: label
            });
        }
        if (e["data"] == YT.PlayerState.ENDED) {
            console.log({
                event: "youtube",
                action: "end",
                label: label
            });
        }
        //track number of buffering and quality of video
        if (e["data"] == YT.PlayerState.BUFFERING) {
            e.target.uBufferingCount?++e.target.uBufferingCount:e.target.uBufferingCount=1; 
            console.log({
                event: "youtube",
                action: "buffering["+e.target.uBufferingCount+"]:"+e.target.getPlaybackQuality(),
                label: label
            });
            //if one video is play then pause other, this is needed because at start video is in buffered state and start playing without go to playing state
            if( YT.PlayerState.UNSTARTED ==  e.target.uLastPlayerState ){
                pauseOthersYoutubes(e.target);
            }
        }
        //last action keep stage in uLastPlayerState
        if( e.data != e.target.uLastPlayerState ) {
            console.log(label + ":state change from " + e.target.uLastPlayerState + " to " + e.data);
            e.target.uLastPlayerState = e.data;
        }
    }
    function initYoutubePlayers(){
        ytplayerList = null; //reset
        ytplayerList = []; //create new array to hold youtube player
        for (var e = document.getElementsByTagName("iframe"), x = e.length; x-- ;) {
            if (/youtube.com\/embed/.test(e[x].src)) {
                ytplayerList.push(initYoutubePlayer(e[x]));
                console.log("create a Youtube player successfully");
            }
        }

    }
    function pauseOthersYoutubes( currentPlayer ) {
        if (!currentPlayer) return;
        for (var i = ytplayerList.length; i-- ;){
            if( ytplayerList[i] && (ytplayerList[i] != currentPlayer) ){
                ytplayerList[i].pauseVideo();
            }
        }  
    }
    //init a youtube iframe
    function initYoutubePlayer(ytiframe){
        console.log("have youtube iframe");
        var ytp = new YT.Player(ytiframe, {
            events: {
                onStateChange: onPlayerStateChange,
                onError: onPlayerError,
                onReady: onPlayerReady
            }
        });
        ytiframe.ytp = ytp;
        return ytp;
    }
    function onYouTubeIframeAPIReady() {
        console.log("YouTubeIframeAPI is ready");
        initYoutubePlayers();
    }
    var tag = document.createElement('script');
    //use https when loading script and youtube iframe src since if user is logging in youtube the youtube src will switch to https.
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);    

  </script>

我建议您将其包含在HTML页面本身中...

以下是该解决方案的实时示例!!!

/*javascipt for the following slider*/
/* Create an array to hold the different image positions */
      var itemPositions = [];
      var numberOfItems = $('#scroller .item').length;
      
      /* Assign each array element a CSS class based on its initial position */
      function assignPositions() {
        for (var i = 0; i < numberOfItems; i++) {
          if (i === 0) {
            itemPositions[i] = 'left-hidden';
          } else if (i === 1) {
            itemPositions[i] = 'left';
          } else if (i === 2) {
            itemPositions[i] = 'middle';
          } else if (i === 3) {
            itemPositions[i] = 'right';
          } else {
            itemPositions[i] = 'right-hidden';
          }
        }
        /* Add each class to the corresponding element */
        $('#scroller .item').each(function(index) {
          $(this).addClass(itemPositions[index]);
        });
      }
      
      /* To scroll, we shift the array values by one place and reapply the classes to the images */
      function scroll(direction) {
        if (direction === 'prev') {
          itemPositions.push(itemPositions.shift());
        } else if (direction === 'next') {
          itemPositions.unshift(itemPositions.pop());
        }
        $('#scroller .item').removeClass('left-hidden left middle right right-hidden').each(function(index) {
          $(this).addClass(itemPositions[index]);
        });
      }
      
      /* Do all this when the DOMs ready */
      $(document).ready(function() {
      
        assignPositions();
        var autoScroll = window.setInterval("scroll('next')", 4000);
      
        /* Hover behaviours */
        $('#scroller').hover(function() {
          window.clearInterval(autoScroll);
          $('.nav').stop(true, true).fadeIn(200);
        }, function() {
          $('.nav').stop(true, true).fadeOut(200);
        });
      
        /* Click behaviours */
        $('.prev').click(function() {
          scroll('prev');
        });
        $('.next').click(function() {
          scroll('next');
        });
      
      });
html {
  scroll-behavior: smooth;
}

body {
  overflow-x: hidden;
  margin: 0;
  padding: 0;
  width: 100vw;
  user-select: none;
  -ms-overflow-style: none;
}

body::-webkit-scrollbar {
  display: none;
}

.carousel {
  background-image: url(carousel1.jpg);
  width: 100vw;
  height: 52.5vw;
  background-size: 100vw 52.5vw;
}

#scroller {
  position: absolute;
  top: 12vw;
  left: 25vw;
  width: 50vw;
  height: 28vw;
  margin: 0 auto;
  padding: 0;
  -webkit-perspective: 40vw;
  -moz-perspective: 50vw;
  -o-perspective: 50vw;
}

#scroller .item {
  width: 50vw;
  height: 28vw;
  display: block;
  position: absolute;
  border-radius: 1vw;
  -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(.85, transparent), to(rgba(255, 255, 255, 0.15)));
  -webkit-transition: all 0.4s ease-in-out;
  -moz-transition: all 0.4s ease-in-out;
  -o-transition: all 0.4s ease-in-out;
  z-index: 0;
}
/* Since inset shadows don't play nice with images, we'll create a pseudo element and apply our image styling to that instead */

#scroller .item .youtube-video {
  display: block;
  border-radius: 1vw;
}

#scroller .left {
  pointer-events: none;
  -webkit-transform: rotateY(25deg) translateX(-320px) skewY(-5deg) scale(0.4, 0.6);
  -moz-transform: rotateY(25deg) translateX(-320px) skewY(-5deg) scale(0.4, 0.6);
  -o-transform: rotateY(25deg) translateX(-320px) skewY(-5deg) scale(0.4, 0.6);
}

#scroller .middle {
  z-index: 1;
  -webkit-transform: rotateY(0deg) translateX(0) scale(1);
  -moz-transform: rotateY(0deg) translateX(0) scale(1);
  -o-transform: rotateY(0deg) translateX(0) scale(1);
}

#scroller .right {
  pointer-events: none;
  -webkit-transform: rotateY(-25deg) translateX(320px) skewY(5deg) scale(0.4, 0.6);
  -moz-transform: rotateY(-25deg) translateX(320px) skewY(5deg) scale(0.4, 0.6);
  -o-transform: rotateY(-25deg) translateX(320px) skewY(5deg) scale(0.4, 0.6);
}

#scroller .left-hidden {
  opacity: 0;
  z-index: -1;
  pointer-events: none;
  -webkit-transform: rotateY(25deg) translateX(-430px) skewY(-5deg) scale(0.3, 0.5);
  -moz-transform: rotateY(25deg) translateX(-430px) skewY(-5deg) scale(0.3, 0.5);
  -o-transform: rotateY(25deg) translateX(-430px) skewY(-5deg) scale(0.3, 0.5);
}

#scroller .right-hidden {
  opacity: 0;
  z-index: -1;
  pointer-events: none;
  -webkit-transform: rotateY(-25deg) translateX(430px) skewY(5deg) scale(0.3, 0.5);
  -moz-transform: rotateY(-25deg) translateX(430px) skewY(5deg) scale(0.3, 0.5);
  -o-transform: rotateY(-25deg) translateX(430px) skewY(5deg) scale(0.3, 0.5);
}

.nav {
  position: absolute;
  width: 50vw;
  height: 2vw;
  margin: 14vw 0 0;
  z-index: 2;
  display: none;
}

.prev,
.next {
  position: absolute;
  display: block;
  height: 2vw;
  width: 2vw;
  background-color: rgba(255, 255, 255, 0.85);
  border-radius: 2vw;
  color: #1d1919;
  bottom: 20px;
  font-size: 2vw;
  text-align: center;
  line-height: 1.5vw;
  cursor: pointer;
  border: 2px solid #000;
}

.prev {
  left: 1vw;
}

.next {
  left: inherit;
  right: 1vw;
}

.prev:hover,
.next:hover {
  border: 0.01vw solid #000;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">    
    <link rel="stylesheet" type="text/css" href="index1.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!-- Load font awesome icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <title>Gully Ball - carousel</title>
    <link rel="icon" href="logo.png" type="image/jpg" sizes="18x18">

  </head>
  <body>
    <div class="carousel">
      <div class="slideshow-container" id="scroller">
  
        <div class="nav">
          <a class="prev">&laquo;</a>
          <a class="next">&raquo;</a>
        </div>
  
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/xOiVl3qaFkw?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/keTYvc-xU64?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div> 
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/ejlFMXU_Lg0?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/73f3QPsm80Y?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/z3L8EqCb958?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/uKkFIjsLVOo?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/W4gVYFMBU88?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/EsU5tKG4rxk?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/DyI57PYkmDA?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/CbZpZpUb_5A?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/yfOsin7OcA0?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/6cJcfVv35oU?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/lTwl7UQN_CQ?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/Sc77-58rtlI?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/GbN5LBNAYMY?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
        <div class="item">
          <iframe class="youtube-video" width="100%" height="100%" src="https://www.youtube.com/embed/UYNwSeupjUM?html5=1&enablejsapi=1;rel=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
      </div>
    </div>  
      <script>
        var ytplayerList;

        function onPlayerReady(e) {
            var video_data = e.target.getVideoData(),
                label = video_data.video_id+':'+video_data.title;
            e.target.ulabel = label;
            console.log(label + " is ready!");
         
        }
        function onPlayerError(e) {
            console.log('[onPlayerError]');
        }
        function onPlayerStateChange(e) {
            var label = e.target.ulabel;
            if (e["data"] == YT.PlayerState.PLAYING) {
                console.log({
                    event: "youtube",
                    action: "play:"+e.target.getPlaybackQuality(),
                    label: label
                });
                //if one video is play then pause other
                pauseOthersYoutubes(e.target);
            }
            if (e["data"] == YT.PlayerState.PAUSED) {
                console.log({
                    event: "youtube",
                    action: "pause:"+e.target.getPlaybackQuality(),
                    label: label
                });
            }
            if (e["data"] == YT.PlayerState.ENDED) {
                console.log({
                    event: "youtube",
                    action: "end",
                    label: label
                });
            }
            //track number of buffering and quality of video
            if (e["data"] == YT.PlayerState.BUFFERING) {
                e.target.uBufferingCount?++e.target.uBufferingCount:e.target.uBufferingCount=1; 
                console.log({
                    event: "youtube",
                    action: "buffering["+e.target.uBufferingCount+"]:"+e.target.getPlaybackQuality(),
                    label: label
                });
                //if one video is play then pause other, this is needed because at start video is in buffered state and start playing without go to playing state
                if( YT.PlayerState.UNSTARTED ==  e.target.uLastPlayerState ){
                    pauseOthersYoutubes(e.target);
                }
            }
            //last action keep stage in uLastPlayerState
            if( e.data != e.target.uLastPlayerState ) {
                console.log(label + ":state change from " + e.target.uLastPlayerState + " to " + e.data);
                e.target.uLastPlayerState = e.data;
            }
        }
        function initYoutubePlayers(){
            ytplayerList = null; //reset
            ytplayerList = []; //create new array to hold youtube player
            for (var e = document.getElementsByTagName("iframe"), x = e.length; x-- ;) {
                if (/youtube.com\/embed/.test(e[x].src)) {
                    ytplayerList.push(initYoutubePlayer(e[x]));
                    console.log("create a Youtube player successfully");
                }
            }
            
        }
        function pauseOthersYoutubes( currentPlayer ) {
            if (!currentPlayer) return;
            for (var i = ytplayerList.length; i-- ;){
                if( ytplayerList[i] && (ytplayerList[i] != currentPlayer) ){
                    ytplayerList[i].pauseVideo();
                }
            }  
        }
        //init a youtube iframe
        function initYoutubePlayer(ytiframe){
            console.log("have youtube iframe");
            var ytp = new YT.Player(ytiframe, {
                events: {
                    onStateChange: onPlayerStateChange,
                    onError: onPlayerError,
                    onReady: onPlayerReady
                }
            });
            ytiframe.ytp = ytp;
            return ytp;
        }
        function onYouTubeIframeAPIReady() {
            console.log("YouTubeIframeAPI is ready");
            initYoutubePlayers();
        }
        var tag = document.createElement('script');
        //use https when loading script and youtube iframe src since if user is logging in youtube the youtube src will switch to https.
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);    
                
      </script>
  </body>
</html>

祝你有美好的一天!
问候,
欧姆乔杜里(Om Chaudhary)

答案 1 :(得分:1)

jsfiddle example演示了如何播放一个视频并暂停另一个视频而无需遍历每个视频。我使用iframe标签显示视频,但是使用javascript初始化视频时也可以应用此逻辑。

var currentPlayer;
var autopaused;
var pnWelwegrNfQ;
var p9HfzcqeS2SU;
var pjDV5q37rGlg;
function onYouTubeIframeAPIReady() {
    pnWelwegrNfQ = new YT.Player('pnWelwegrNfQ', {
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    p9HfzcqeS2SU = new YT.Player('p9HfzcqeS2SU', {
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    pjDV5q37rGlg = new YT.Player('pjDV5q37rGlg', {
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
}
function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PAUSED && currentPlayer != undefined && event.target == currentPlayer) {
        autopaused = undefined;
        currentPlayer = undefined;
    } else if (event.data == YT.PlayerState.PAUSED && autopaused != undefined && (event.target == autopaused && event.target != currentPlayer)) {
        autopaused = undefined;
    } else if (event.data == YT.PlayerState.PLAYING && event.target != autopaused) {
        autopaused = currentPlayer;
        if (autopaused != undefined) {
            currentPlayer = event.target;
            autopaused.pauseVideo();
        } else {
            currentPlayer = event.target;
        }
    } else if (autopaused != undefined && event.target == autopaused) {
        autopaused = undefined;
    }
}

答案 2 :(得分:0)

您可以尝试实现如下代码:

 <div id="player1"></div>
 <div id="player2"></div>
 <!-- add as many as you need -->
 <script>
   var tag = document.createElement('script');
   tag.src = "//www.youtube.com/iframe_api";
   var firstScriptTag = document.getElementsByTagName('script')[0];
   firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player={};
function onYouTubeIframeAPIReady() {
    player.player1 = new YT.Player('player1', {
        height: '293',
        width: '520',
        videoId: 'zXV8GMSc5Vg',
        events: {
            'onStateChange': onPlayerStateChange
        }
    });
    player.player2 = new YT.Player('player2', {
        height: '293',
        width: '520',
        videoId: 'LTy0TzA_4DQ',
        events: {
            'onStateChange': onPlayerStateChange
        }
    });

}

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {
        pauseVideos(event.target.a.id); 
    }
}

function pauseVideos(player_id) {
    for (p in player) {
        if (p!==player_id) {
          player[p].pauseVideo(); // all videos will pause playing except the one that triggered the event
        }
    }
}
</script>

您只需要为每个玩家设置姓名以拥有自己的身份,以便在有条件的情况下轻松实现此目的。我了解您只是想为您的玩家打个动态电话,但是如果您想拥有这样的条件,这将很困难。尝试根据此更改您的代码。我实际上已经尝试在onPlayerStateChange()上实现此功能,但是由于event.target的玩家名称相同,因此我无法制定适当的条件。希望这会有所帮助!