最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I control the playback of multiple Youtube Videos with the Youtube JS api? - Stack Overflow

programmeradmin0浏览0评论

Here's the problem: I have multiple youtube videos in a slider, and I want the videos to stop playing when a link that controls the slider is clicked. It's really annoying to have the videos just keep playing when you can't see it.

I used this code:

<div id="ytapiplayer2">
    You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script type="text/javascript">
    function onYouTubePlayerReady(playerId) {ytplayer2 = document.getElementById("myvideo");}
    var params = { allowScriptAccess: "always" };var atts = { id: "myvideo" };
    swfobject.embedSWF(";version=3&playerapiid=myvideo","ytapiplayer2", "425", "270", "8", null, null, params, atts);
    function play() {if (ytplayer2) {ytplayer2.playVideo();}}
    function pause() {if (ytplayer2) {ytplayer2.pauseVideo();}}
</script>

Which is basically directly from Google's Youtube js api stuff.1 It works GREAT for just ONE video, per page.

My problem is I have some pages where I want to have multiple videos in the same slider. Videos are contained within divs, and called exactly as shown above in each respective div.

BUT -- The videos don't stop playing back now when navigating links for the slider are clicked. :(

I have tried to change the variable and id names to be unique each time the script is called. I have even changed the function name from function onYouTubePlayerReady to onYouTubePlayerReady2 ... but nothing works.

I'm stumped. Halp?


Edit to show more detailed code set up:

<head>
<script src=".6.0/jquery.min.js" type="text/javascript"></script><!--Uses Google API library-->
<script src=".2/swfobject.js" type="text/javascript"></script><!--Uses Google API library-->
</head>
<body>
<div id="bodyContent">
    <div id="leftCol">
        Content
    </div><!-- #leftCol -->
        <div id="middleCol">
        <ul id="subNav">
                 <li class="category">Mini Header</li>
                 <li><a href="#link1">Link 1</a></li>
                 <li><a href="#link2">Link 2</a></li>
                 <li><a href="#link3">Link 3</a></li>
        </ul><!--subNav-->
                </div><!-- #middleCol -->
                <div id="rightCol" class="slider">
                    <div class="scroll">
                        <div class="scrollContainer">                  
                            <div id="link1" class="panel">
                            <div id="ytapiplayer1">
                                You need Flash player 8+ and JavaScript enabled to view this video.
                                </div>
                                <script type="text/javascript">
                                function onYouTubePlayerReady(playerId) {ytplayer1 = document.getElementById("myVideo1");}
                                var params = { allowScriptAccess: "always" };var atts = { id: "myVideo1" };
                                swfobject.embedSWF(";version=3&playerapiid=ytplayer1","ytapiplayer1", "425", "347", "8", null, null, params, atts);
                                function play() {if (ytplayer1) {ytplayer1.playVideo();}}
                                function pause() {if (ytplayer1) {ytplayer1.pauseVideo();}}
                                </script>
                            </div><!-- #link1 -->
                            <div id="link2" class="panel">
                            <div id="ytapiplayer2">
                                You need Flash player 8+ and JavaScript enabled to view this video.
                                </div>
                                <script type="text/javascript">
                                function onYouTubePlayerReady(playerId) {ytplayer2 = document.getElementById("myVideo2");}
                                var params = { allowScriptAccess: "always" };var atts = { id: "myVideo2" };
                                swfobject.embedSWF(";version=3&playerapiid=ytplayer1","ytapiplayer2", "425", "347", "8", null, null, params, atts);
                                function play() {if (ytplayer2) {ytplayer2.playVideo();}}
                                function pause() {if (ytplayer2) {ytplayer2.pauseVideo();}}
                                </script>
                            </div><!-- #link2 -->
                    <div>Video 3 set up is same as above...</div>
                        </div>
                    </div><!-- .scroll -->
                </div><!-- #rightCol -->
</div><!-- #bodyContent -->
</body>

Here's the problem: I have multiple youtube videos in a slider, and I want the videos to stop playing when a link that controls the slider is clicked. It's really annoying to have the videos just keep playing when you can't see it.

I used this code:

<div id="ytapiplayer2">
    You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script type="text/javascript">
    function onYouTubePlayerReady(playerId) {ytplayer2 = document.getElementById("myvideo");}
    var params = { allowScriptAccess: "always" };var atts = { id: "myvideo" };
    swfobject.embedSWF("http://www.youtube./v/hCarSDT7cSQ?enablejsapi=1&version=3&playerapiid=myvideo","ytapiplayer2", "425", "270", "8", null, null, params, atts);
    function play() {if (ytplayer2) {ytplayer2.playVideo();}}
    function pause() {if (ytplayer2) {ytplayer2.pauseVideo();}}
</script>

Which is basically directly from Google's Youtube js api stuff.1 It works GREAT for just ONE video, per page.

My problem is I have some pages where I want to have multiple videos in the same slider. Videos are contained within divs, and called exactly as shown above in each respective div.

BUT -- The videos don't stop playing back now when navigating links for the slider are clicked. :(

I have tried to change the variable and id names to be unique each time the script is called. I have even changed the function name from function onYouTubePlayerReady to onYouTubePlayerReady2 ... but nothing works.

I'm stumped. Halp?


Edit to show more detailed code set up:

<head>
<script src="https://ajax.googleapis./ajax/libs/jquery/1.6.0/jquery.min.js" type="text/javascript"></script><!--Uses Google API library-->
<script src="http://ajax.googleapis./ajax/libs/swfobject/2.2/swfobject.js" type="text/javascript"></script><!--Uses Google API library-->
</head>
<body>
<div id="bodyContent">
    <div id="leftCol">
        Content
    </div><!-- #leftCol -->
        <div id="middleCol">
        <ul id="subNav">
                 <li class="category">Mini Header</li>
                 <li><a href="#link1">Link 1</a></li>
                 <li><a href="#link2">Link 2</a></li>
                 <li><a href="#link3">Link 3</a></li>
        </ul><!--subNav-->
                </div><!-- #middleCol -->
                <div id="rightCol" class="slider">
                    <div class="scroll">
                        <div class="scrollContainer">                  
                            <div id="link1" class="panel">
                            <div id="ytapiplayer1">
                                You need Flash player 8+ and JavaScript enabled to view this video.
                                </div>
                                <script type="text/javascript">
                                function onYouTubePlayerReady(playerId) {ytplayer1 = document.getElementById("myVideo1");}
                                var params = { allowScriptAccess: "always" };var atts = { id: "myVideo1" };
                                swfobject.embedSWF("http://www.youtube./v/67aIIRv-dYU?enablejsapi=1&version=3&playerapiid=ytplayer1","ytapiplayer1", "425", "347", "8", null, null, params, atts);
                                function play() {if (ytplayer1) {ytplayer1.playVideo();}}
                                function pause() {if (ytplayer1) {ytplayer1.pauseVideo();}}
                                </script>
                            </div><!-- #link1 -->
                            <div id="link2" class="panel">
                            <div id="ytapiplayer2">
                                You need Flash player 8+ and JavaScript enabled to view this video.
                                </div>
                                <script type="text/javascript">
                                function onYouTubePlayerReady(playerId) {ytplayer2 = document.getElementById("myVideo2");}
                                var params = { allowScriptAccess: "always" };var atts = { id: "myVideo2" };
                                swfobject.embedSWF("http://www.youtube./v/67aIIRv-dYU?enablejsapi=1&version=3&playerapiid=ytplayer1","ytapiplayer2", "425", "347", "8", null, null, params, atts);
                                function play() {if (ytplayer2) {ytplayer2.playVideo();}}
                                function pause() {if (ytplayer2) {ytplayer2.pauseVideo();}}
                                </script>
                            </div><!-- #link2 -->
                    <div>Video 3 set up is same as above...</div>
                        </div>
                    </div><!-- .scroll -->
                </div><!-- #rightCol -->
</div><!-- #bodyContent -->
</body>
Share Improve this question edited Jun 22, 2011 at 10:55 Salman Arshad 272k84 gold badges443 silver badges534 bronze badges asked Jun 20, 2011 at 3:07 lzheidilzheidi 432 silver badges6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Wrong approach. Why use two or more YouTube players when you can acplish the task with one player, specially when you're using YouTube JS API.

Relevant code:

<div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<a href="#" onclick="load('hCarSDT7cSQ'); return false;">Video 1</a>
<a href="#" onclick="load('67aIIRv-dYU'); return false;">Video 2</a>

<script type="text/javascript">
function load(id) {
    if (ytplayer) {
        ytplayer.loadVideoById(id);
    }
}
</script>

Demo for solution 1

Alternately you can create multiple players and figure out some way of storing how many players you have on the page in a variable. I think it is sufficient to store the id of the player. Do not confuse the id with (i) the id you assign to the div (ii) the id you pass as playerapiid.

swfobject.embedSWF() will replace the div with either an object or embed tag, that tag is assigned an id that you pass to this method in the last parameter. This is the id that you can later use to reference the player(s).

Demo for solution 2

<script type="text/javascript" src="http://www.youtube./player_api"></script>
<script>                
    var player1st;
    var player2nd;
    function onYouTubePlayerAPIReady() { 
    player1st = new YT.Player('frame1st', {events: {'onStateChange': onPlayerStateChange}}); 
    player2nd = new YT.Player('frame2nd', {events: {'onStateChange': onPlayerStateChange}});
        }              
    //function onYouTubePlayerAPIReady() { player2nd = new YT.Player('frame2nd', {events: {'onStateChange': onPlayerStateChange}}); }                
    function onPlayerStateChange(event) {
    alert(event.target.getPlayerState());        
    }        
</script>                        
<iframe id="frame1st" style="position: relative; height: 220px; width: 400px" src="http://www.youtube./embed/1g30Xyh6Wqc?rel=0&amp;enablejsapi=1"></iframe><br>
<a href="javascript: void(0)" onclick="player1st.playVideo(); return false">play1st</a><br>
<a href="javascript: void(0)" onclick="player1st.pauseVideo(); return false">pause1st</a><br>
<a href="javascript: void(0)" onclick="player1st.stopVideo(); return false">stop1st</a>                
<iframe id="frame2nd" style="position: relative; height: 220px; width: 400px" src="http://www.youtube./embed/T39hYJAwR40?rel=0&amp;enablejsapi=1"></iframe><br>    
<a href="javascript: void(0)" onclick="player2nd.playVideo(); return false">play2nd</a><br>
<a href="javascript: void(0)" onclick="player2nd.pauseVideo(); return false">pause2nd</a><br>
<a href="javascript: void(0)" onclick="player2nd.stopVideo(); return false">stop2nd</a>

Store the references to each player in an array, then when you want to stop them all loop through the array. If you could post more of your HTML/JavaScript for the multiple video setup I might have a more specific suggestion, otherwise fill in the blanks yourself:

// add a global array of video refs
var myVideos = [];

// some code to create the first video, similar to OP code
// ...
myVideos.push(ytplayer2);

// some code to create second video
// ...
myVideos.push(anotherVideoRef);

// some code to create third video
// ...
myVideos.push(thirdVideoRef);

// etc.

function pauseAllVideos(){
   for (var i = 0; i < myVideos.length; i++) {
      myVideos[i].pauseVideo();
   }
}

I would prefer to setup the videos in a loop, rather than one at a time like I did above, but I don't know how the rest of your code is structured, so...

发布评论

评论列表(0)

  1. 暂无评论