开发者

Catch the event when a youtube flash video is done playing using javascript

开发者 https://www.devze.com 2023-02-06 00:27 出处:网络
I\'m supposed to create a sort of youtube video rotator using jquery. I\'ve looked around and there seemed to be no plugin that\'s fit for the requirement. Not even a solution.

I'm supposed to create a sort of youtube video rotator using jquery. I've looked around and there seemed to be no plugin that's fit for the requirement. Not even a solution.

Maybe I'll开发者_运维问答 just try to make this. So now, how can I determine that a youtube video is done playing and automatically play the next, using Jquery, or simply just javascript?

And if you happen to know a plugin which may help, please point out.

Thanks


First you have to make sure the youtube player you're embedding supports javascript by passing enablejsapi=1 as a get param. Here's how I insert a (chromeless) player using SWFObject:

    var player_id = "your_player_id";
    var params = { allowScriptAccess: "always" };
    var url = "http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=" + player_id;
    swfobject.embedSWF(url, player_id, '320', '240', "9.0.0", null, null, params, {'id': player_id});

Then you need to add a global function that is called when the player is ready, and in that add a listener for when a video is complete:

    var player = null;

    function onYouTubePlayerReady(player_id) {
      player = document.getElementById(player_id);
      player.addEventListener('onStateChange', 'playerStateChanged');
      player.loadVideoById(youtube_video_id);
    };

    function playerStateChanged(state) {
      // State code 0 means playback ended
      if (state == 0) {
        player.loadVideoById(next_video_id);
      }
    };

I wrote this code for my youtube playlist bookmarklet. Here's a link if you want a working example: http://zaius.github.com/youtube_playlist/

And if you want to do anything more in depth, here's the youtube javascript reference where I worked out how to do all this: http://code.google.com/apis/youtube/js_api_reference.html

0

精彩评论

暂无评论...
验证码 换一张
取 消