YouTube Player API Reference for iframe Embeds

iFrame प्लेयर एपीआई की मदद से, अपनी वेबसाइट पर YouTube वीडियो प्लेयर को एम्बेड किया जा सकता है. साथ ही, JavaScript का इस्तेमाल करके प्लेयर को कंट्रोल किया जा सकता है.

एपीआई के JavaScript फ़ंक्शन का इस्तेमाल करके, वीडियो चलाने के लिए सूची बनाई जा सकती है. साथ ही, उन वीडियो को चलाया, रोका या बंद किया जा सकता है. इसके अलावा, प्लेयर की आवाज़ को कम या ज़्यादा किया जा सकता है या चल रहे वीडियो की जानकारी हासिल की जा सकती है. आपके पास इवेंट लिसनर जोड़ने का विकल्प भी है. ये लिसनर, प्लेयर के कुछ इवेंट के जवाब में काम करेंगे. जैसे, प्लेयर की स्थिति में बदलाव होना.

इस गाइड में, IFrame API का इस्तेमाल करने का तरीका बताया गया है. यह उन अलग-अलग तरह के इवेंट की पहचान करता है जिन्हें एपीआई भेज सकता है. साथ ही, उन इवेंट का जवाब देने के लिए, इवेंट लिसनर लिखने का तरीका भी बताता है. इसमें अलग-अलग JavaScript फ़ंक्शन के बारे में भी बताया गया है. इन फ़ंक्शन का इस्तेमाल करके, वीडियो प्लेयर को कंट्रोल किया जा सकता है. साथ ही, प्लेयर पैरामीटर का इस्तेमाल करके, प्लेयर को पसंद के मुताबिक बनाया जा सकता है.

ज़रूरी शर्तें

उपयोगकर्ता के ब्राउज़र में, HTML5 postMessage सुविधा काम करती हो. ज़्यादातर आधुनिक ब्राउज़र में postMessage काम करता है.

एम्बेड किए गए प्लेयर का व्यूपोर्ट कम से कम 200 x 200 पिक्सल का होना चाहिए. अगर प्लेयर में कंट्रोल दिखते हैं, तो वे ज़रूरत के मुताबिक बड़े होने चाहिए, ताकि वे व्यूपोर्ट को कम से कम साइज़ से छोटा किए बिना पूरी तरह से दिख सकें. हमारा सुझाव है कि 16:9 आसपेक्ट रेशियो वाले प्लेयर कम से कम 480 पिक्सल चौड़े और 270 पिक्सल लंबे होने चाहिए.

IFrame API का इस्तेमाल करने वाले किसी भी वेब पेज को, यह JavaScript फ़ंक्शन भी लागू करना होगा:

  • onYouTubeIframeAPIReady – जब पेज, प्लेयर एपीआई के लिए JavaScript डाउनलोड कर लेगा, तब एपीआई इस फ़ंक्शन को कॉल करेगा. इसके बाद, पेज पर एपीआई का इस्तेमाल किया जा सकेगा. इसलिए, यह फ़ंक्शन ऐसे प्लेयर ऑब्जेक्ट बना सकता है जिन्हें आपको पेज लोड होने पर दिखाना है.

शुरू करना

यहां दिए गए सैंपल HTML पेज में, एम्बेड किया गया प्लेयर बनाया गया है. यह प्लेयर, वीडियो को लोड करके छह सेकंड तक चलाएगा और फिर उसे बंद कर देगा. एचटीएमएल में नंबर वाली टिप्पणियों के बारे में, उदाहरण के नीचे दी गई सूची में बताया गया है.

<!DOCTYPE html>
<html>
  <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player"></div>

    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          playerVars: {
            'playsinline': 1
          },
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }

      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          setTimeout(stopVideo, 6000);
          done = true;
        }
      }
      function stopVideo() {
        player.stopVideo();
      }
    </script>
  </body>
</html>

ऊपर दिए गए सैंपल के बारे में ज़्यादा जानकारी यहां दी गई है:

  1. इस सेक्शन में मौजूद

    टैग, पेज पर उस जगह की पहचान करता है जहां IFrame API, वीडियो प्लेयर को डालेगा. प्लेयर ऑब्जेक्ट के कन्स्ट्रक्टर, जिसे वीडियो प्लेयर लोड करना सेक्शन में बताया गया है, वह
    टैग की पहचान उसके id से करता है. इससे यह पक्का होता है कि एपीआई,

    इस उदाहरण में, इस कोड का इस्तेमाल किया गया है:

    <iframe id="existing-iframe-example"
            width="640" height="360"
            src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
            frameborder="0"
            style="border: solid 4px #37474F"
    ></iframe>
    
    <script type="text/javascript">
      var tag = document.createElement('script');
      tag.id = 'iframe-demo';
      tag.src = 'https://www.youtube.com/iframe_api';
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('existing-iframe-example', {
            events: {
              'onReady': onPlayerReady,
              'onStateChange': onPlayerStateChange
            }
        });
      }
      function onPlayerReady(event) {
        document.getElementById('existing-iframe-example').style.borderColor = '#FF6D00';
      }
      function changeBorderColor(playerStatus) {
        var color;
        if (playerStatus == -1) {
          color = "#37474F"; // unstarted = gray
        } else if (playerStatus == 0) {
          color = "#FFFF00"; // ended = yellow
        } else if (playerStatus == 1) {
          color = "#33691E"; // playing = green
        } else if (playerStatus == 2) {
          color = "#DD2C00"; // paused = red
        } else if (playerStatus == 3) {
          color = "#AA00FF"; // buffering = purple
        } else if (playerStatus == 5) {
          color = "#FF6DOO"; // video cued = orange
        }
        if (color) {
          document.getElementById('existing-iframe-example').style.borderColor = color;
        }
      }
      function onPlayerStateChange(event) {
        changeBorderColor(event.data);
      }
    </script>
  2. उदाहरण 2: तेज़ आवाज़ में वीडियो चलाना

    इस उदाहरण में, 1280 पिक्सल x 720 पिक्सल का वीडियो प्लेयर बनाया गया है. इसके बाद, onReady इवेंट के लिए इवेंट लिसनर, वॉल्यूम को सबसे ज़्यादा सेटिंग पर अडजस्ट करने के लिए setVolume फ़ंक्शन को कॉल करता है.

    function onYouTubeIframeAPIReady() {
      var player;
      player = new YT.Player('player', {
        width: 1280,
        height: 720,
        videoId: 'M7lc1UVf-VE',
        events: {
          'onReady': onPlayerReady,
          'onStateChange': onPlayerStateChange,
          'onError': onPlayerError
        }
      });
    }
    
    function onPlayerReady(event) {
      event.target.setVolume(100);
      event.target.playVideo();
    }
  3. तीसरा उदाहरण: इस उदाहरण में, वीडियो लोड होने पर उसे अपने-आप चलाने और वीडियो प्लेयर के कंट्रोल छिपाने के लिए, प्लेयर पैरामीटर सेट किए गए हैं. यह एपीआई के ब्रॉडकास्ट किए जाने वाले कई इवेंट के लिए, इवेंट लिसनर भी जोड़ता है.

    function onYouTubeIframeAPIReady() {
      var player;
      player = new YT.Player('player', {
        videoId: 'M7lc1UVf-VE',
        playerVars: { 'autoplay': 1, 'controls': 0 },
        events: {
          'onReady': onPlayerReady,
          'onStateChange': onPlayerStateChange,
          'onError': onPlayerError
        }
      });
    }
  4. 360° वीडियो को कंट्रोल करना

    इस उदाहरण में, इस कोड का इस्तेमाल किया गया है:

    <style>
      .current-values {
        color: #666;
        font-size: 12px;
      }
    </style>
    <!-- The player is inserted in the following div element -->
    <div id="spherical-video-player"></div>
    
    <!-- Display spherical property values and enable user to update them. -->
    <table style="border: 0; width: 640px;">
      <tr style="background: #fff;">
        <td>
          <label for="yaw-property">yaw: </label>
          <input type="text" id="yaw-property" style="width: 80px"><br>
          <div id="yaw-current-value" class="current-values"> </div>
        </td>
        <td>
          <label for="pitch-property">pitch: </label>
          <input type="text" id="pitch-property" style="width: 80px"><br>
          <div id="pitch-current-value" class="current-values"> </div>
        </td>
        <td>
          <label for="roll-property">roll: </label>
          <input type="text" id="roll-property" style="width: 80px"><br>
          <div id="roll-current-value" class="current-values"> </div>
        </td>
        <td>
          <label for="fov-property">fov: </label>
          <input type="text" id="fov-property" style="width: 80px"><br>
          <div id="fov-current-value" class="current-values"> </div>
        </td>
        <td style="vertical-align: bottom;">
          <button id="spherical-properties-button">Update properties</button>
        </td>
      </tr>
    </table>
    
    <script type="text/javascript">
      var tag = document.createElement('script');
      tag.id = 'iframe-demo';
      tag.src = 'https://www.youtube.com/iframe_api';
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
      var PROPERTIES = ['yaw', 'pitch', 'roll', 'fov'];
      var updateButton = document.getElementById('spherical-properties-button');
    
      // Create the YouTube Player.
      var ytplayer;
      function onYouTubeIframeAPIReady() {
        ytplayer = new YT.Player('spherical-video-player', {
            height: '360',
            width: '640',
            videoId: 'FAtdv94yzp4',
        });
      }
    
      // Don't display current spherical settings because there aren't any.
      function hideCurrentSettings() {
        for (var p = 0; p < PROPERTIES.length; p++) {
          document.getElementById(PROPERTIES[p] + '-current-value').innerHTML = '';
        }
      }
    
      // Retrieve current spherical property values from the API and display them.
      function updateSetting() {
        if (!ytplayer || !ytplayer.getSphericalProperties) {
          hideCurrentSettings();
        } else {
          let newSettings = ytplayer.getSphericalProperties();
          if (Object.keys(newSettings).length === 0) {
            hideCurrentSettings();
          } else {
            for (var p = 0; p < PROPERTIES.length; p++) {
              if (newSettings.hasOwnProperty(PROPERTIES[p])) {
                currentValueNode = document.getElementById(PROPERTIES[p] +
                                                           '-current-value');
                currentValueNode.innerHTML = ('current: ' +
                    newSettings[PROPERTIES[p]].toFixed(4));
              }
            }
          }
        }
        requestAnimationFrame(updateSetting);
      }
      updateSetting();
    
      // Call the API to update spherical property values.
      updateButton.onclick = function() {
        var sphericalProperties = {};
        for (var p = 0; p < PROPERTIES.length; p++) {
          var propertyInput = document.getElementById(PROPERTIES[p] + '-property');
          sphericalProperties[PROPERTIES[p]] = parseFloat(propertyInput.value);
        }
        ytplayer.setSphericalProperties(sphericalProperties);
      }
    </script>

    Android WebView Media Integrity API का इंटिग्रेशन

    YouTube ने Android वेबव्यू मीडिया इंटिग्रिटी एपीआई को अपडेट किया है. इससे, एम्बेड किए गए मीडिया प्लेयर को चालू किया जा सकेगा. इनमें, Android ऐप्लिकेशन में एम्बेड किए गए YouTube प्लेयर भी शामिल हैं. इससे, एम्बेड करने वाले ऐप्लिकेशन की पुष्टि की जा सकेगी. इस बदलाव के बाद, एम्बेड किए गए ऐप्लिकेशन, YouTube को अपने-आप एक पुष्टि किया गया ऐप्लिकेशन आईडी भेजते हैं. इस एपीआई के इस्तेमाल से इकट्ठा किया गया डेटा, ऐप्लिकेशन का मेटाडेटा (पैकेज का नाम, वर्शन नंबर, और साइनिंग सर्टिफ़िकेट) और Google Play services से जनरेट किया गया डिवाइस की पुष्टि करने वाला टोकन होता है.

    इस डेटा का इस्तेमाल, ऐप्लिकेशन और डिवाइस की इंटिग्रिटी की पुष्टि करने के लिए किया जाता है. इसे एन्क्रिप्ट (सुरक्षित) किया जाता है और तीसरे पक्षों के साथ शेयर नहीं किया जाता. साथ ही, इसे तय समय के बाद मिटा दिया जाता है. ऐप्लिकेशन डेवलपर, WebView Media Integrity API में अपने ऐप्लिकेशन की पहचान कॉन्फ़िगर कर सकते हैं. कॉन्फ़िगरेशन में ऑप्ट-आउट करने का विकल्प होता है.

    संशोधन इतिहास

    June 24, 2024

    The documentation has been updated to note that YouTube has extended the Android WebView Media Integrity API to enable embedded media players, including YouTube player embeds in Android applications, to verify the embedding app's authenticity. With this change, embedding apps automatically send an attested app ID to YouTube.

    November 20, 2023

    The new onAutoplayBlocked event API is now available. This event notifies your application if the browser blocks autoplay or scripted playback. Verification of autoplay success or failure is an established paradigm for HTMLMediaElements, and the onAutoplayBlocked event now provides similar functionality for the IFrame Player API.

    April 27, 2021

    The Getting Started and Loading a Video Player sections have been updated to include examples of using a playerVars object to customize the player.

    October 13, 2020

    Note: This is a deprecation announcement for the embedded player functionality that lets you configure the player to load search results. This announcement affects the IFrame Player API's queueing functions for lists, cuePlaylist and loadPlaylist.

    This change will become effective on or after 15 November 2020. After that time, calls to the cuePlaylist or loadPlaylist functions that set the listType property to search will generate a 4xx response code, such as 404 (Not Found) or 410 (Gone). This change also affects the list property for those functions as that property no longer supports the ability to specify a search query.

    As an alternative, you can use the YouTube Data API's search.list method to retrieve search results and then load selected videos in the player.

    October 24, 2019

    The documentation has been updated to reflect the fact that the API no longer supports functions for setting or retrieving playback quality. As explained in this YouTube Help Center article, to give you the best viewing experience, YouTube adjusts the quality of your video stream based on your viewing conditions.

    The changes explained below have been in effect for more than one year. This update merely aligns the documentation with current functionality:

    • The getPlaybackQuality, setPlaybackQuality, and getAvailableQualityLevels functions are no longer supported. In particular, calls to setPlaybackQuality will be no-op functions, meaning they will not actually have any impact on the viewer's playback experience.
    • The queueing functions for videos and playlists -- cueVideoById, loadVideoById, etc. -- no longer support the suggestedQuality argument. Similarly, if you call those functions using object syntax, the suggestedQuality field is no longer supported. If suggestedQuality is specified, it will be ignored when the request is handled. It will not generate any warnings or errors.
    • The onPlaybackQualityChange event is still supported and might signal a change in the viewer's playback environment. See the Help Center article referenced above for more information about factors that affect playback conditions or that might cause the event to fire.

    May 16, 2018

    The API now supports features that allow users (or embedders) to control the viewing perspective for 360° videos:

    • The getSphericalProperties function retrieves the current orientation for the video playback. The orientation includes the following data:
      • yaw - represents the horizontal angle of the view in degrees, which reflects the extent to which the user turns the view to face further left or right
      • pitch - represents the vertical angle of the view in degrees, which reflects the extent to which the user adjusts the view to look up or down
      • roll - represents the rotational angle (clockwise or counterclockwise) of the view in degrees.
      • fov - represents the field-of-view of the view in degrees, which reflects the extent to which the user zooms in or out on the video.
    • The setSphericalProperties function modifies the view to match the submitted property values. In addition to the orientation values described above, this function supports a Boolean field that indicates whether the IFrame embed should respond to DeviceOrientationEvents on supported mobile devices.

    This example demonstrates and lets you test these new features.

    June 19, 2017

    This update contains the following changes:

    • Documentation for the YouTube Flash Player API and YouTube JavaScript Player API has been removed and redirected to this document. The deprecation announcement for the Flash and JavaScript players was made on January 27, 2015. If you haven't done so already, please migrate your applications to use IFrame embeds and the IFrame Player API.

    August 11, 2016

    This update contains the following changes:

    • The newly published YouTube API Services Terms of Service ("the Updated Terms"), discussed in detail on the YouTube Engineering and Developers Blog, provides a rich set of updates to the current Terms of Service. In addition to the Updated Terms, which will go into effect as of February 10, 2017, this update includes several supporting documents to help explain the policies that developers must follow.

      The full set of new documents is described in the revision history for the Updated Terms. In addition, future changes to the Updated Terms or to those supporting documents will also be explained in that revision history. You can subscribe to an RSS feed listing changes in that revision history from a link in that document.

    June 29, 2016

    This update contains the following changes:

    • The documentation has been corrected to note that the onApiChange method provides access to the captions module and not the cc module.

    June 24, 2016

    The Examples section has been updated to include an example that demonstrates how to use the API with an existing tag since the onYouTubeIframeAPIReady function is only called if the closing element is present.

    August 6, 2012

    This update contains the following changes:

    • The Operations section has been expanded to list all of the supported API functions rather than linking to the JavaScript Player API Reference for that list.

    • The API supports several new functions and one new event that can be used to control the video playback speed:

      • Functions

        • getAvailablePlaybackRates – Retrieve the supported playback rates for the cued or playing video. Note that variable playback rates are currently only supported in the HTML5 player.
        • getPlaybackRate – Retrieve the playback rate for the cued or playing video.
        • setPlaybackRate – Set the playback rate for the cued or playing video.

      • Events

    July 19, 2012

    This update contains the following changes:

    • The new getVideoLoadedFraction method replaces the now-deprecated getVideoBytesLoaded and getVideoBytesTotal methods. The new method returns the percentage of the video that the player shows as buffered.

    • The onError event may now return an error code of 5, which indicates that the requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.

    • The Requirements section has been updated to indicate that any web page using the IFrame API must also implement the onYouTubeIframeAPIReady function. Previously, the section indicated that the required function was named onYouTubePlayerAPIReady. Code samples throughout the document have also been updated to use the new name.

      Note: To ensure that this change does not break existing implementations, both names will work. If, for some reason, your page has an onYouTubeIframeAPIReady function and an onYouTubePlayerAPIReady function, both functions will be called, and the onYouTubeIframeAPIReady function will be called first.

    • The code sample in the Getting started section has been updated to reflect that the URL for the IFrame Player API code has changed to http://www.youtube.com/iframe_api. To ensure that this change does not affect existing implementations, the old URL (http://www.youtube.com/player_api) will continue to work.

    July 16, 2012

    This update contains the following changes:

    • The Operations section now explains that the API supports the setSize() and destroy() methods. The setSize() method sets the size in pixels of the