Search code examples
youtubeyoutube-javascript-apiandroid-youtube-apiyoutube-data-api

embed and loop just a part of a youtube video (html5)


Is there a way to loop just a part of a YouTube video with the HTML5 player? I tried this code (start 7 sec, end 12sec)

The first "loop" shows the part I want, second and other loops shows the whole video.

It is working in Flash but I have issues in HTML 5 for mobile devices.

Here is my embed code:

<iframe allowfullscreen="" frameborder="0"  width="960" height="720" src="http://www.youtube.com/embed/Bpu0TIXzI1w?version=3&start=7&end=12&amp;autohide=1&amp;hl=en_US&amp;rel=0&amp;loop=0&amp;modestbranding=1&amp;playlist=Bpu0TIXzI1w"></iframe>

Solution

  • You may need to use the Javascript API. It's a bit more complex, but you have full control over the video playback.

    Documentation: https://developers.google.com/youtube/iframe_api_reference

    Working example: http://jsfiddle.net/pbosakov/Lo6gwtff/

    Code:

    <div id="player"></div>
    <script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>
    <script type="text/javascript">
    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'Bpu0TIXzI1w',
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }
    function onPlayerReady(event) {
        loopStart();
        player.playVideo();
    }
    function loopStart() {
        player.seekTo(7);   // Start at 7 seconds
    }
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING) {
            setTimeout(loopStart, 5000); // After 5 seconds, restart the loop
        }
    }
    </script>