Company Blog RSS Feed

Detecting video player state with YouTube JavaScript Player API

July 24, 2010
If you need to implement a way in your application to prevent users from proceeding to the following step or section until they have viewed an entire video, then read on!

First, embed your video link using the following code:

<script width="425" height="344">
    <param name="movie" value="(movieLocationHere)"></param>
    <param name="allowscriptaccess" value="always"></param>

    <script id="video" src="(movieLocationHere)" type="application/x-shockwave-flash" allowscriptaccess="always" width="425" height="344">
    </embed>
</object>


Make sure to replace (movieLocationHere) with the actual location of your movie. Also, in this code, you will need to append the following portion to the end of your video's URL:

?enablejsapi=1


This ensures that the JavaScript API is enabled, otherwise the JavaScript functions explained next will not work.

This portion of code checks the current state of your video player:

<script type="text/javascript">
    function PlayerState() {
        var sStatus = document.getElementById("video").getPlayerState();
        if (sStatus == -1) alert ("Video has not started.");
        else if (sStatus == 0) alert ("Video has ended.");
        else if (sStatus == 1) alert ("Video is playing.");
        else if (sStatus == 2) alert ("Video is paused.");
        else if (sStatus == 3) alert ("Video is buffering.");
        else if (sStatus == 5) alert ("Video is cued.");
    }
</script>


The getPlayerState() function returns an integer. These values are specified below with their meanings:

-1 - Video has not started yet.
0 - Video has ended.
1 - Video is currently playing.
2 - Video has been paused.
3 - Video is buffering.
5 - Video is cued.


The following button is needed to check the current player state at will:

<input type="button" value="Get Player State" onclick="javascript:PlayerState();">


This button calls the getPlayerState() function previously defined in your JavaScript code and returns the current player state. If you want your application to halt until the entire video is played, then you can set up your JavaScript function to perform this action once the getPlayerState() function returns a value of zero.

For more information on the YouTube JavaScript Player API, visit this link: http://code.google.com/apis/youtube/js_api_reference.html



Add A Comment





Subscribe to this blog