Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  95] [ 2]  / answers: 1 / hits: 20173  / 12 Years ago, mon, february 18, 2013, 12:00:00

I have multiple YouTube iFrames embedded on a page. If one of the movies is already playing, and a user then decides to start playing a different movie, is it possible to stop playing the first movie so there is only ever one playing at a time?



I have looked at the 'YouTube Player API Reference for iframe Embeds' https://developers.google.com/youtube/iframe_api_reference but if i'm honest I just don't understand it. My developer skills are very limited.... clearly.



Pitiful I know, but this is all I have at the moment (just the iFrames)... http://jsfiddle.net/YGMUJ/



<iframe width=520 height=293 src=http://www.youtube.com/v/zXV8GMSc5Vg?version=3&enablejsapi=1 frameborder=0 allowfullscreen></iframe>
<iframe width=520 height=293 src=http://www.youtube.com/v/LTy0TzA_4DQ?version=3&enablejsapi=1 frameborder=0 allowfullscreen></iframe>


I thought all I needed to do was add '&enablejsapi=1' at the end of the video URLs.



Any help would be much appreciated.

Thank you in advance.


More From » iframe

 Answers
62

Instead of using iframes, you actually want to use the iFrame Player API. Depending on how many videos you actually wanted to embed, you might want to make this javascript more dynamic, but this working example should give you enough to get started.



Basically what I'm doing here is initializing the two players, and pausing the opposite video when a player state changes to play.



You can play with the following code at http://jsfiddle.net/mattkoskela/Whxjx/



<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() {
player1 = new YT.Player('player1', {
height: '293',
width: '520',
videoId: 'zXV8GMSc5Vg',
events: {
'onStateChange': onPlayerStateChange
}
});
player2 = new YT.Player('player2', {
height: '293',
width: '520',
videoId: 'LTy0TzA_4DQ',
events: {
'onStateChange': onPlayerStateChange
}
});
}

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

function stopVideo(player_id) {
if (player_id == player1) {
player2.stopVideo();
} else if (player_id == player2) {
player1.stopVideo();
}
}



[#80150] Sunday, February 17, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cody

Total Points: 679
Total Questions: 111
Total Answers: 111

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;