js api

How to mute and autoplay youtube video using JS API

Now I am going to tell you how to mute and autoplay a YouTube video using YouTube JavaScript API. Its a good idea if someone don’t want to disturb the viewers by making the video silent while auto playing.

To accomplish this task you need to understand the YouTube JavaScript API. Google suggest to use swfobject embed SWF and to detect user’s flash player version.

<script src="http://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js"></script>
<div id="ytapiplayer">You need Flash player 8+ and JavaScript enabled to view this video.</div>
<script type="text/javascript">
    google.load("swfobject", "2.1");
    function onYouTubePlayerReady(playerId) {
        ytplayer = document.getElementById("myytplayer");
    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    "ytapiplayer", "425", "356", "8", null, null, params, atts);

How this works:

In the above code i firstly included the necessary JavaScript files one is Google’s JavaScript API at line 1 and the other is swfobject at line 2. Then on line 3 I create a DIV that will be displayed if the user’s flash player version is is not atleast 8. On line 5, I loaded the swf object using the google load method. Line 7 gets the player id, Line 8 plays the video and line 8 finaly mutes the video. Lines 7,8,9 are contained in function onYouTubePlayerReady which is automatically called when the youtube video is ready to play. Line 11 I allowScriptAccess paramater is set to always this allows the JavaScript to community with the video player. Line 12 defines the player Id which you get at line 7. And finally you embed your video by passing the full URL and the parameters which are self explanatory.

You can copy paste this code to and make experiments. For more details please visit: http://code.google.com/apis/youtube/js_api_reference.html to view the more API parameters.

Happy YouTube Integration with Auto-played Muted video :)

Tags: , , , , , , ,

Tuesday, October 19th, 2010 API, YouTube 7 Comments