YouTube Player API Reference for iframe Embeds

IFrame player API به شما امکان می دهد یک پخش کننده ویدیوی YouTube را در وب سایت خود جاسازی کنید و پخش کننده را با استفاده از جاوا اسکریپت کنترل کنید.

با استفاده از توابع جاوا اسکریپت API، می توانید ویدیوها را برای پخش در صف قرار دهید. پخش، مکث یا توقف آن ویدیوها؛ تنظیم صدای پخش کننده؛ یا اطلاعات مربوط به ویدیوی در حال پخش را بازیابی کنید. همچنین می‌توانید شنونده‌های رویدادی را اضافه کنید که در پاسخ به رویدادهای پخش کننده خاص، مانند تغییر وضعیت پخش، اجرا می‌شوند.

این راهنما نحوه استفاده از IFrame API را توضیح می دهد. انواع مختلف رویدادهایی را که API می‌تواند ارسال کند را شناسایی می‌کند و نحوه نوشتن شنوندگان رویداد برای پاسخ به آن رویدادها را توضیح می‌دهد. همچنین توابع مختلف جاوا اسکریپت را که می‌توانید برای کنترل پخش‌کننده ویدیو فراخوانی کنید و همچنین پارامترهای پخش‌کننده‌ای را که می‌توانید برای سفارشی‌سازی بیشتر پخش‌کننده استفاده کنید، توضیح می‌دهد.

الزامات

مرورگر کاربر باید از ویژگی postMessage HTML5 پشتیبانی کند. اکثر مرورگرهای مدرن از postMessage پشتیبانی می کنند.

Embedded players must have a viewport that is at least 200px by 200px. If the player displays controls, it must be large enough to fully display the controls without shrinking the viewport below the minimum size. We recommend 16:9 players be at least 480 pixels wide and 270 pixels tall.

هر صفحه وب که از API IFrame استفاده می کند باید تابع جاوا اسکریپت زیر را نیز پیاده سازی کند:

  • onYouTubeIframeAPIReady – وقتی صفحه دانلود جاوا اسکریپت برای API پخش کننده تمام شد، API این تابع را فراخوانی می کند، که به شما امکان می دهد سپس از API در صفحه خود استفاده کنید. بنابراین، این تابع ممکن است اشیاء پخش کننده ای را ایجاد کند که می خواهید هنگام بارگیری صفحه نمایش دهید.

شروع شدن

صفحه نمونه HTML زیر یک پخش کننده تعبیه شده ایجاد می کند که یک ویدیو را بارگیری می کند، آن را به مدت شش ثانیه پخش می کند و سپس پخش را متوقف می کند. نظرات شماره گذاری شده در 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. تگ <div> در این بخش مکانی را در صفحه ای که API IFrame پخش کننده ویدیو را در آن قرار می دهد، مشخص می کند. سازنده شی پخش کننده، که در بخش Loading a video player توضیح داده شده است، تگ <div> را با id خود شناسایی می کند تا مطمئن شود که API <iframe> را در مکان مناسب قرار می دهد. به طور خاص، IFrame API تگ <div> را با تگ <iframe> جایگزین می کند.

    به عنوان جایگزین، می‌توانید عنصر <iframe> را مستقیماً در صفحه قرار دهید. بخش Loading a video player نحوه انجام این کار را توضیح می دهد.

  2. کد موجود در این بخش کد جاوا اسکریپت API IFrame Player را بارگیری می کند. مثال از اصلاح DOM برای دانلود کد API استفاده می کند تا اطمینان حاصل شود که کد به صورت ناهمزمان بازیابی می شود. (ویژگی async تگ <script> ، که دانلودهای ناهمزمان را نیز فعال می کند، هنوز در همه مرورگرهای مدرن پشتیبانی نمی شود، همانطور که در این پاسخ Stack Overflow بحث شد.

  3. عملکرد onYouTubeIframeAPIReady به محض دانلود کد API پخش کننده اجرا می شود. این بخش از کد یک متغیر سراسری، player تعریف می کند، که به پخش کننده ویدیویی که در حال تعبیه آن هستید اشاره دارد و سپس تابع، شی پخش کننده ویدیو را می سازد.

  4. تابع onPlayerReady زمانی اجرا می شود که رویداد onReady فعال شود. در این مثال، عملکرد نشان می دهد که وقتی پخش کننده ویدیو آماده است، باید شروع به پخش کند.

  5. API تابع onPlayerStateChange را هنگامی که وضعیت بازیکن تغییر می‌کند، فراخوانی می‌کند، که ممکن است نشان‌دهنده این باشد که پخش‌کننده در حال بازی کردن، توقف، تمام شدن و غیره است. این عملکرد نشان می دهد که وقتی وضعیت پخش 1 است (در حال پخش)، پخش کننده باید به مدت شش ثانیه پخش شود و سپس تابع stopVideo را فراخوانی کند تا ویدیو متوقف شود.

در حال بارگیری یک پخش کننده ویدیو

پس از بارگیری کد جاوا اسکریپت API، API تابع onYouTubeIframeAPIReady را فراخوانی می کند، در این مرحله می توانید یک شی YT.Player برای درج یک پخش کننده ویدیو در صفحه خود بسازید. گزیده HTML زیر تابع onYouTubeIframeAPIReady را از مثال بالا نشان می دهد:

var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: 'M7lc1UVf-VE',
    playerVars: {
      'playsinline': 1
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

سازنده برای پخش کننده ویدیو پارامترهای زیر را مشخص می کند:

  1. پارامتر اول یا عنصر DOM یا id عنصر HTML را مشخص می کند که در آن API تگ <iframe> حاوی پخش کننده را درج می کند.

    IFrame API عنصر مشخص شده را با عنصر <iframe> حاوی پخش کننده جایگزین می کند. اگر عنصری که جایگزین می شود سبک نمایش متفاوتی نسبت به عنصر درج شده <iframe> داشته باشد، می تواند روی طرح بندی صفحه شما تأثیر بگذارد. به طور پیش‌فرض، یک <iframe> به عنوان یک عنصر inline-block نمایش داده می‌شود.

  2. پارامتر دوم یک شی است که گزینه های پخش کننده را مشخص می کند. شی شامل ویژگی های زیر است:
    • width (عدد) - عرض پخش کننده ویدیو. مقدار پیش فرض 640 است.
    • height (تعداد) - ارتفاع پخش کننده ویدیو. مقدار پیش فرض 390 است.
    • videoId (رشته) - شناسه ویدیوی YouTube که ویدیویی را که پخش کننده بارگذاری می کند، مشخص می کند.
    • playerVars (شیء) - ویژگی های شیء پارامترهای پخش کننده را شناسایی می کند که می توان از آنها برای سفارشی کردن پخش کننده استفاده کرد.
    • events (شیء) - ویژگی های شیء رویدادهایی را که API اجرا می کند و توابع (شنونده های رویداد) را که API هنگام وقوع آن رویدادها فراخوانی می کند، مشخص می کند. در مثال، سازنده نشان می‌دهد که تابع onPlayerReady زمانی اجرا می‌شود که رویداد onReady فعال می‌شود و تابع onPlayerStateChange زمانی که رویداد onStateChange فعال می‌شود، اجرا می‌شود.

همانطور که در بخش شروع به کار ذکر شد، به جای نوشتن یک عنصر خالی <div> در صفحه خود، که کد جاوا اسکریپت API پخش کننده با عنصر <iframe> جایگزین می شود، می توانید تگ <iframe> را خودتان ایجاد کنید. اولین مثال در بخش Examples نحوه انجام این کار را نشان می دهد.

<iframe id="player" type="text/html" width="640" height="390"
  src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
  frameborder="0"></iframe>

توجه داشته باشید که اگر تگ <iframe> را می‌نویسید، وقتی شی YT.Player را می‌سازید، نیازی به تعیین مقادیر برای width و height ندارید که به عنوان ویژگی‌های تگ <iframe> یا videoId مشخص می‌شوند. و پارامترهای پخش کننده، که در URL src مشخص شده اند. به عنوان یک اقدام امنیتی اضافی، باید پارامتر origin را نیز به URL وارد کنید و طرح URL ( http:// یا https:// ) و دامنه کامل صفحه میزبان خود را به عنوان مقدار پارامتر مشخص کنید. در حالی که origin اختیاری است، از جمله در برابر تزریق جاوا اسکریپت شخص ثالث مخرب به صفحه شما و ربودن کنترل پخش کننده YouTube شما محافظت می کند.

بخش Examples همچنین چند مثال دیگر را برای ساخت اشیاء پخش کننده ویدیو نشان می دهد.

عملیات

برای فراخوانی متدهای پخش کننده API، ابتدا باید یک مرجع به شی پخش کننده ای که می خواهید کنترل کنید، دریافت کنید. شما مرجع را با ایجاد یک شیء YT.Player همانطور که در بخش شروع و بارگیری یک پخش کننده ویدیو در این سند توضیح داده شده است، به دست می آورید.

کارکرد

توابع صف

عملکردهای صف به شما امکان بارگیری و پخش یک ویدیو، یک لیست پخش یا لیست دیگری از ویدیوها را می دهند. اگر از دستور شیء توضیح داده شده در زیر برای فراخوانی این توابع استفاده می کنید، می توانید لیستی از ویدیوهای آپلود شده کاربر را نیز در صف قرار دهید یا بارگذاری کنید.

API از دو نحو مختلف برای فراخوانی توابع صف پشتیبانی می کند.

  • نحو آرگومان نیاز دارد که آرگومان های تابع به ترتیبی تعیین شده فهرست شوند.

  • نحو شی به شما امکان می دهد یک شی را به عنوان یک پارامتر واحد ارسال کنید و ویژگی های شی را برای آرگومان های تابعی که می خواهید تنظیم کنید تعریف کنید. علاوه بر این، API ممکن است از عملکرد اضافی پشتیبانی کند که نحو آرگومان از آن پشتیبانی نمی کند.

برای مثال، تابع loadVideoById را می توان به یکی از روش های زیر فراخوانی کرد. توجه داشته باشید که نحو شی از ویژگی endSeconds پشتیبانی می کند، که نحو آرگومان آن را پشتیبانی نمی کند.

  • نحو آرگومان

    loadVideoById("bHQqvYy5KYo", 5, "large")
  • نحو شی

    loadVideoById({'videoId': 'bHQqvYy5KYo',
                   'startSeconds': 5,
                   'endSeconds': 60});

توابع صف برای فیلم ها

cueVideoById
  • نحو آرگومان

    player.cueVideoById(videoId:String,
                        startSeconds:Number):Void
  • نحو شی

    player.cueVideoById({videoId:String,
                         startSeconds:Number,
                         endSeconds:Number}):Void

این عملکرد تصویر کوچک ویدیوی مشخص شده را بارگیری می کند و پخش کننده را برای پخش ویدیو آماده می کند. پخش کننده تا زمانی که playVideo() یا seekTo() فراخوانی نشود، FLV را درخواست نمی کند.

  • پارامتر videoId مورد نیاز، شناسه ویدیوی YouTube را برای پخش مشخص می کند. در YouTube Data API، ویژگی id یک منبع video ، شناسه را مشخص می‌کند.
  • پارامتر اختیاری startSeconds یک float/integer را می‌پذیرد و زمانی را مشخص می‌کند که پس از فراخوانی playVideo() باید پخش ویدیو شروع شود. اگر مقدار startSeconds را مشخص کنید و سپس seekTo() فراخوانی کنید، پخش کننده از زمان مشخص شده در فراخوان seekTo() بازی می کند. هنگامی که ویدیو آماده شد و برای پخش آماده شد، پخش کننده یک رویداد video cued را پخش خواهد کرد ( 5 ).
  • پارامتر اختیاری endSeconds ، که فقط در نحو شی پشتیبانی می‌شود، یک عدد float/integer را می‌پذیرد و زمانی را مشخص می‌کند که با فراخوانی playVideo() پخش ویدیو متوقف شود. اگر مقدار endSeconds را مشخص کنید و سپس seekTo() را فراخوانی کنید، مقدار endSeconds دیگر اعمال نخواهد شد.

loadVideoById

  • نحو آرگومان

    player.loadVideoById(videoId:String,
                         startSeconds:Number):Void
  • نحو شی

    player.loadVideoById({videoId:String,
                          startSeconds:Number,
                          endSeconds:Number}):Void

این تابع ویدیوی مشخص شده را بارگیری و پخش می کند.

  • پارامتر videoId مورد نیاز، شناسه ویدیوی YouTube را برای پخش مشخص می کند. در YouTube Data API، ویژگی id یک منبع video ، شناسه را مشخص می‌کند.
  • پارامتر اختیاری startSeconds یک float/integer را می پذیرد. اگر مشخص باشد، ویدئو از نزدیکترین فریم کلیدی به زمان مشخص شده شروع می شود.
  • پارامتر اختیاری endSeconds یک float/integer را می پذیرد. اگر مشخص شده باشد، پخش ویدیو در زمان مشخص شده متوقف می شود.

cueVideoByUrl

  • نحو آرگومان

    player.cueVideoByUrl(mediaContentUrl:String,
                         startSeconds:Number):Void
  • نحو شی

    player.cueVideoByUrl({mediaContentUrl:String,
                          startSeconds:Number,
                          endSeconds:Number}):Void

این عملکرد تصویر کوچک ویدیوی مشخص شده را بارگیری می کند و پخش کننده را برای پخش ویدیو آماده می کند. پخش کننده تا زمانی که playVideo() یا seekTo() فراخوانی نشود، FLV را درخواست نمی کند.

  • پارامتر mediaContentUrl مورد نیاز یک URL پخش کننده YouTube کاملا واجد شرایط را در قالب http://www.youtube.com/v/VIDEO_ID?version=3 مشخص می کند.
  • پارامتر اختیاری startSeconds یک float/integer را می‌پذیرد و زمانی را مشخص می‌کند که پس از فراخوانی playVideo() باید پخش ویدیو شروع شود. اگر startSeconds را مشخص کنید و سپس seekTo() را فراخوانی کنید، سپس پخش کننده از زمان مشخص شده در فراخوان seekTo() پخش می شود. هنگامی که ویدئو آماده شد و برای پخش آماده شد، پخش کننده یک رویداد video cued (5) را پخش خواهد کرد.
  • پارامتر اختیاری endSeconds ، که فقط در نحو شی پشتیبانی می‌شود، یک عدد float/integer را می‌پذیرد و زمانی را مشخص می‌کند که با فراخوانی playVideo() پخش ویدیو متوقف شود. اگر مقدار endSeconds را مشخص کنید و سپس seekTo() را فراخوانی کنید، مقدار endSeconds دیگر اعمال نخواهد شد.

loadVideoByUrl

  • نحو آرگومان

    player.loadVideoByUrl(mediaContentUrl:String,
                          startSeconds:Number):Void
  • نحو شی

    player.loadVideoByUrl({mediaContentUrl:String,
                           startSeconds:Number,
                           endSeconds:Number}):Void

این تابع ویدیوی مشخص شده را بارگیری و پخش می کند.

  • پارامتر mediaContentUrl مورد نیاز یک URL پخش کننده YouTube کاملا واجد شرایط را در قالب http://www.youtube.com/v/VIDEO_ID?version=3 مشخص می کند.
  • پارامتر اختیاری startSeconds یک float/integer را می‌پذیرد و زمان شروع پخش ویدیو را مشخص می‌کند. اگر startSeconds (عدد می تواند شناور باشد) مشخص شده باشد، ویدیو از نزدیکترین فریم کلیدی به زمان مشخص شده شروع می شود.
  • پارامتر اختیاری endSeconds ، که فقط در نحو شی پشتیبانی می‌شود، یک عدد شناور/صحیح را می‌پذیرد و زمان توقف پخش ویدیو را مشخص می‌کند.

توابع صف برای لیست ها

توابع cuePlaylist و loadPlaylist به شما این امکان را می دهند که یک لیست پخش را بارگیری و پخش کنید. اگر از دستور شی برای فراخوانی این توابع استفاده می کنید، می توانید لیستی از ویدیوهای آپلود شده کاربر را نیز در صف قرار دهید (یا بارگذاری کنید).

از آنجایی که توابع بسته به اینکه با استفاده از نحو آرگومان فراخوانی شوند یا نحو شیء متفاوت عمل می کنند، هر دو روش فراخوانی در زیر مستند شده اند.

cuePlaylist
  • نحو آرگومان

    player.cuePlaylist(playlist:String|Array,
                       index:Number,
                       startSeconds:Number):Void
    لیست پخش مشخص شده را در صف قرار می دهد. وقتی لیست پخش آماده شد و برای پخش آماده شد، پخش کننده یک رویداد video cued را پخش می کند ( 5 ).
    • پارامتر playlist مورد نیاز آرایه ای از شناسه های ویدیوی YouTube را مشخص می کند. در YouTube Data API، ویژگی id منبع video ، شناسه آن ویدیو را مشخص می‌کند.

    • پارامتر index اختیاری، نمایه اولین ویدیویی را که در لیست پخش پخش می‌شود، مشخص می‌کند. این پارامتر از یک شاخص مبتنی بر صفر استفاده می کند و مقدار پارامتر پیش فرض 0 است، بنابراین رفتار پیش فرض بارگیری و پخش اولین ویدیو در لیست پخش است.

    • پارامتر اختیاری startSeconds یک عدد float/integer را می‌پذیرد و زمانی را مشخص می‌کند که اولین ویدیو در لیست پخش با فراخوانی تابع playVideo() باید پخش شود. اگر مقدار startSeconds را مشخص کنید و سپس seekTo() فراخوانی کنید، پخش کننده از زمان مشخص شده در فراخوان seekTo() بازی می کند. اگر یک لیست پخش را انتخاب کنید و سپس تابع playVideoAt() را فراخوانی کنید، پخش کننده در ابتدای ویدیوی مشخص شده شروع به پخش می کند.

  • نحو شی

    player.cuePlaylist({listType:String,
                        list:String,
                        index:Number,
                        startSeconds:Number}):Void
    لیست مشخص شده ویدیوها را در صف قرار می دهد. این لیست می تواند یک لیست پخش یا فید ویدیوهای آپلود شده کاربر باشد. قابلیت صف‌بندی فهرستی از نتایج جستجو منسوخ شده است و از 15 نوامبر 2020 دیگر پشتیبانی نخواهد شد.

    هنگامی که لیست آماده شد و برای پخش آماده شد، پخش کننده یک رویداد video cued را پخش می کند ( 5 ).

    • ویژگی اختیاری listType نوع فید نتایجی را که بازیابی می کنید مشخص می کند. مقادیر معتبر playlist و user_uploads هستند. یک مقدار منسوخ، search ، از 15 نوامبر 2020 دیگر پشتیبانی نخواهد شد. مقدار پیش فرض playlist است.

    • ویژگی list مورد نیاز حاوی کلیدی است که لیست خاصی از ویدیوهایی را که YouTube باید برگرداند را مشخص می کند.

      • اگر مقدار ویژگی listType playlist باشد، ویژگی list شناسه لیست پخش یا آرایه ای از شناسه های ویدیو را مشخص می کند. در YouTube Data API، ویژگی id منبع playlist ، شناسه فهرست پخش را مشخص می‌کند، و ویژگی id منبع video ، شناسه ویدیو را مشخص می‌کند.
      • اگر مقدار ویژگی listType user_uploads باشد، ویژگی list کاربری را مشخص می کند که ویدیوهای آپلود شده او برگردانده می شوند.
      • اگر مقدار ویژگی listType search باشد، ویژگی list عبارت جستجو را مشخص می کند. توجه: این عملکرد منسوخ شده است و از 15 نوامبر 2020 دیگر پشتیبانی نخواهد شد.

    • ویژگی index اختیاری، نمایه اولین ویدیویی که در لیست پخش می شود را مشخص می کند. این پارامتر از یک شاخص مبتنی بر صفر استفاده می کند و مقدار پارامتر پیش فرض 0 است، بنابراین رفتار پیش فرض بارگیری و پخش اولین ویدیو در لیست است.

    • ویژگی اختیاری startSeconds یک عدد float/integer را می‌پذیرد و زمانی را مشخص می‌کند که اولین ویدیوی لیست باید از آن زمان شروع به پخش کند که تابع playVideo() فراخوانی شود. اگر مقدار startSeconds را مشخص کنید و سپس seekTo() فراخوانی کنید، پخش کننده از زمان مشخص شده در فراخوان seekTo() بازی می کند. اگر لیستی را علامت بزنید و سپس تابع playVideoAt() را فراخوانی کنید، پخش کننده در ابتدای ویدیوی مشخص شده شروع به پخش می کند.

loadPlaylist
  • نحو آرگومان

    player.loadPlaylist(playlist:String|Array,
                        index:Number,
                        startSeconds:Number):Void
    این تابع لیست پخش مشخص شده را بارگیری می کند و آن را پخش می کند.
    • پارامتر playlist مورد نیاز آرایه ای از شناسه های ویدیوی YouTube را مشخص می کند. در YouTube Data API، ویژگی id منبع video ، شناسه ویدیو را مشخص می‌کند.

    • پارامتر index اختیاری، نمایه اولین ویدیویی را که در لیست پخش پخش می‌شود، مشخص می‌کند. این پارامتر از یک شاخص مبتنی بر صفر استفاده می کند و مقدار پارامتر پیش فرض 0 است، بنابراین رفتار پیش فرض بارگیری و پخش اولین ویدیو در لیست پخش است.

    • پارامتر اختیاری startSeconds یک float/integer را می‌پذیرد و زمانی را مشخص می‌کند که اولین ویدیو در لیست پخش باید از آن زمان شروع به پخش کند.

  • نحو شی

    player.loadPlaylist({list:String,
                         listType:String,
                         index:Number,
                         startSeconds:Number}):Void
    این تابع لیست مشخص شده را بارگیری می کند و آن را پخش می کند. این لیست می تواند یک لیست پخش یا فید ویدیوهای آپلود شده کاربر باشد. امکان بارگیری فهرستی از نتایج جستجو منسوخ شده است و از 15 نوامبر 2020 دیگر پشتیبانی نخواهد شد.
    • ویژگی اختیاری listType نوع فید نتایجی را که بازیابی می کنید مشخص می کند. مقادیر معتبر playlist و user_uploads هستند. یک مقدار منسوخ، search ، از 15 نوامبر 2020 دیگر پشتیبانی نخواهد شد. مقدار پیش فرض playlist است.

    • ویژگی list مورد نیاز حاوی کلیدی است که لیست خاصی از ویدیوهایی را که YouTube باید برگرداند را مشخص می کند.

      • اگر مقدار ویژگی listType playlist باشد، ویژگی list یک شناسه لیست پخش یا آرایه‌ای از شناسه‌های ویدیو را مشخص می‌کند. در YouTube Data API، ویژگی id منبع playlist ، شناسه فهرست پخش را مشخص می‌کند، و ویژگی id منبع video ، شناسه ویدیو را مشخص می‌کند.
      • اگر مقدار ویژگی listType user_uploads باشد، ویژگی list کاربری را مشخص می کند که ویدیوهای آپلود شده او برگردانده می شوند.
      • اگر مقدار ویژگی listType search باشد، ویژگی list عبارت جستجو را مشخص می کند. توجه: این عملکرد منسوخ شده است و از 15 نوامبر 2020 دیگر پشتیبانی نخواهد شد.

    • ویژگی index اختیاری، نمایه اولین ویدیویی که در لیست پخش می شود را مشخص می کند. این پارامتر از یک شاخص مبتنی بر صفر استفاده می کند و مقدار پارامتر پیش فرض 0 است، بنابراین رفتار پیش فرض بارگیری و پخش اولین ویدیو در لیست است.

    • ویژگی اختیاری startSeconds یک float/integer را می‌پذیرد و زمانی را مشخص می‌کند که اولین ویدیوی فهرست باید پخش شود.

کنترل های پخش و تنظیمات پخش کننده

پخش یک ویدیو

player. playVideo ():Void
ویدیوی نمایش داده شده/بارگذاری شده فعلی را پخش می کند. حالت نهایی پخش کننده پس از اجرای این تابع در playing (1) خواهد بود.

توجه: بازپخش تنها در صورتی در تعداد بازدیدهای رسمی ویدیو به حساب می آید که از طریق دکمه پخش بومی در پخش کننده شروع شود.
player. pauseVideo ():Void
ویدیوی در حال پخش را متوقف می کند. حالت نهایی پخش کننده پس از اجرای این تابع paused می شود ( 2 ) مگر اینکه هنگام فراخوانی تابع، پخش کننده در حالت ended ( 0 ) باشد، در این صورت وضعیت پخش تغییر نخواهد کرد.
player. stopVideo ():Void
بارگیری ویدیوی فعلی را متوقف و لغو می کند. این عملکرد باید برای موقعیت‌های نادری که می‌دانید کاربر ویدیوی اضافی را در پخش‌کننده تماشا نخواهد کرد، رزرو شود. اگر قصد شما توقف موقت ویدیو است، فقط باید تابع pauseVideo را فراخوانی کنید. اگر می‌خواهید ویدیویی را که پخش‌کننده در حال پخش است تغییر دهید، می‌توانید بدون تماس با stopVideo ابتدا یکی از عملکردهای صف را فراخوانی کنید.

مهم: برخلاف عملکرد pauseVideo که پخش کننده را در حالت paused ( 2 ) قرار می دهد، عملکرد stopVideo می تواند پخش کننده را در حالت عدم پخش قرار دهد، از جمله ended ( 0paused ( 2video cued ( 5 ) یا unstarted ( -1 ).
player. seekTo (seconds:Number, allowSeekAhead:Boolean):Void
به دنبال زمان مشخصی در ویدیو است. اگر پخش کننده هنگام فراخوانی عملکرد متوقف شود، متوقف می شود. اگر عملکرد از حالت دیگری فراخوانی شود ( playing ، video cued ، و غیره)، پخش کننده ویدیو را پخش می کند.
  • پارامتر seconds زمانی را مشخص می کند که بازیکن باید تا آن پیش برود.

    پخش‌کننده قبل از آن زمان به نزدیک‌ترین فریم کلیدی می‌رود، مگر اینکه پخش‌کننده قبلاً بخشی از ویدیویی را که کاربر به دنبال آن است دانلود کرده باشد.

  • پارامتر allowSeekAhead تعیین می‌کند که اگر پارامتر seconds زمانی خارج از داده‌های ویدئویی بافر فعلی را مشخص کند، پخش‌کننده درخواست جدیدی به سرور ارسال کند یا خیر.

    توصیه می‌کنیم زمانی که کاربر ماوس را در نوار پیشرفت ویدیو می‌کشد، این پارامتر را روی false تنظیم کنید و زمانی که کاربر ماوس را رها کرد، آن را روی true تنظیم کنید. این رویکرد به کاربر اجازه می‌دهد تا با پیمایش نقاط بافر نشده در ویدیو، به نقاط مختلف ویدیو بدون درخواست پخش جریانی جدید ویدیو پیمایش کند. هنگامی که کاربر دکمه ماوس را رها می کند، پخش کننده به نقطه مورد نظر در ویدیو پیش می رود و در صورت لزوم درخواست پخش ویدیوی جدید می کند.

کنترل پخش ویدیوهای 360 درجه

توجه: تجربه پخش ویدیوی 360 درجه در دستگاه های تلفن همراه پشتیبانی محدودی دارد. در دستگاه‌های پشتیبانی‌نشده، ویدیوهای 360 درجه تحریف شده به نظر می‌رسند و اصلاً هیچ روش پشتیبانی‌شده‌ای برای تغییر زاویه دید وجود ندارد، از جمله از طریق API، استفاده از حسگرهای جهت‌یابی، یا پاسخ به اقدامات لمسی/کشیدن روی صفحه‌نمایش دستگاه.

player. getSphericalProperties ():Object
ویژگی هایی را بازیابی می کند که دیدگاه یا نمای فعلی بیننده را برای پخش ویدیو توصیف می کند. علاوه بر این:
  • این شی فقط برای ویدیوهای 360 درجه پر شده است که به آنها ویدیوهای کروی نیز می گویند.
  • اگر ویدیوی فعلی یک ویدیوی 360 درجه نیست یا اگر عملکرد از یک دستگاه پشتیبانی نشده فراخوانی شود، تابع یک شی خالی را برمی‌گرداند.
  • در دستگاه‌های تلفن همراه پشتیبانی‌شده، اگر ویژگی enableOrientationSensor روی true تنظیم شود، این تابع یک شی را برمی‌گرداند که در آن ویژگی fov حاوی مقدار صحیح است و سایر ویژگی‌ها روی 0 تنظیم شده‌اند.
شی شامل ویژگی های زیر است:
خواص
yaw عددی در محدوده [0، 360) که زاویه افقی دید را بر حسب درجه نشان می‌دهد، که نشان‌دهنده میزان چرخش کاربر به سمت چپ یا راست است. موقعیت خنثی، رو به مرکز ویدیو در نمای مستطیلی آن، نشان دهنده 0 درجه است، و این مقدار با چرخش بیننده به چپ افزایش می یابد.
pitch عددی در محدوده [90-، 90] که زاویه عمودی دید را بر حسب درجه نشان می‌دهد، که نشان‌دهنده میزانی است که کاربر نما را برای نگاه کردن به بالا یا پایین تنظیم می‌کند. موقعیت خنثی، رو به مرکز ویدیو در طرح ریزی مستطیل شکل آن، نشان دهنده 0 درجه است، و این مقدار با نگاه کردن بیننده به بالا افزایش می یابد.
roll عددی در محدوده [-180، 180] که زاویه چرخش در جهت عقربه‌های ساعت یا خلاف جهت عقربه‌های ساعت را بر حسب درجه نشان می‌دهد. موقعیت خنثی، با محور افقی در برآمدگی مستطیل شکل موازی با محور افقی نما، نشان دهنده 0 درجه است. با چرخش نما در جهت عقربه‌های ساعت، مقدار افزایش می‌یابد و با چرخش نما در خلاف جهت عقربه‌های ساعت، مقدار آن کاهش می‌یابد.

توجه داشته باشید که پخش کننده تعبیه شده یک رابط کاربری برای تنظیم رول نمایش ارائه نمی دهد. رول را می توان به یکی از این روش های متقابل منحصر به فرد تنظیم کرد:
  1. از حسگر جهت یابی در مرورگر تلفن همراه برای ارائه رول برای نما استفاده کنید. اگر سنسور جهت گیری فعال باشد، تابع getSphericalProperties همیشه 0 به عنوان مقدار ویژگی roll برمی گرداند.
  2. اگر سنسور جهت غیرفعال است، با استفاده از این API، رول را روی یک مقدار غیر صفر تنظیم کنید.
fov عددی در محدوده [30، 120] که میدان دید نمای را بر حسب درجه نشان می‌دهد که در امتداد لبه بلندتر نمای درگاه اندازه‌گیری می‌شود. لبه کوتاه‌تر به‌طور خودکار تنظیم می‌شود تا متناسب با نسبت تصویر باشد.

مقدار پیش فرض 100 درجه است. کاهش مقدار مانند بزرگنمایی محتوای ویدیویی است و افزایش مقدار مانند بزرگنمایی است. این مقدار را می توان با استفاده از API یا با استفاده از چرخ ماوس هنگامی که ویدیو در حالت تمام صفحه است تنظیم کرد.
player. setSphericalProperties (properties:Object):Void
جهت ویدیو را برای پخش یک ویدیوی 360 درجه تنظیم می کند. (اگر ویدیوی فعلی کروی نباشد، روش بدون در نظر گرفتن ورودی، بدون عملیات است.)

نمای پخش کننده با به روز رسانی به فراخوانی های این روش پاسخ می دهد تا مقادیر هر ویژگی شناخته شده در شیء properties را منعکس کند. این view مقادیری را برای هر ویژگی شناخته شده دیگری که در آن شی گنجانده نشده است حفظ می کند.

علاوه بر این:
  • اگر شی حاوی ویژگی های ناشناخته و/یا غیرمنتظره باشد، بازیکن آنها را نادیده می گیرد.
  • همانطور که در ابتدای این بخش ذکر شد، تجربه پخش ویدیوی 360 درجه در همه دستگاه های تلفن همراه پشتیبانی نمی شود.
  • به‌طور پیش‌فرض، در دستگاه‌های تلفن همراه پشتیبانی‌شده، این تابع مجموعه‌ها فقط ویژگی fov را تنظیم می‌کند و بر ویژگی‌های yaw ، pitch و roll برای پخش ویدیوی 360 درجه تأثیر نمی‌گذارد. برای جزئیات بیشتر به ویژگی enableOrientationSensor در زیر مراجعه کنید.
شیء properties ارسال شده به تابع حاوی ویژگی های زیر است:
خواص
yaw به تعریف بالا مراجعه کنید.
pitch به تعریف بالا مراجعه کنید.
roll به تعریف بالا مراجعه کنید.
fov به تعریف بالا مراجعه کنید.
enableOrientationSensor توجه: این ویژگی فقط بر روی تجربه مشاهده 360 درجه در دستگاه های پشتیبانی شده تأثیر می گذارد. یک مقدار بولی که نشان می‌دهد آیا تعبیه‌شده IFrame باید به رویدادهایی که سیگنال تغییرات در جهت دستگاه پشتیبانی‌شده را نشان می‌دهند، مانند DeviceOrientationEvent مرورگر تلفن همراه پاسخ دهد. مقدار پارامتر پیش فرض true است.

دستگاه های تلفن همراه پشتیبانی شده
  • وقتی مقدار true باشد، پخش‌کننده تعبیه‌شده تنها به حرکت دستگاه تکیه می‌کند تا ویژگی‌های yaw ، pitch و roll را برای پخش ویدیوی 360 درجه تنظیم کند. با این حال، ویژگی fov را هنوز می توان از طریق API تغییر داد، و API در واقع تنها راه برای تغییر ویژگی fov در یک دستگاه تلفن همراه است. این رفتار به طور پیش فرض است.
  • وقتی مقدار false است، حرکت دستگاه بر تجربه مشاهده 360 درجه تأثیر نمی‌گذارد و ویژگی‌های yaw ، pitch ، roll و fov همگی باید از طریق API تنظیم شوند.

دستگاه های تلفن همراه پشتیبانی نشده
مقدار ویژگی enableOrientationSensor هیچ تاثیری بر تجربه پخش ندارد.

پخش یک ویدیو در لیست پخش

player. nextVideo ():Void
این تابع ویدیوی بعدی را در لیست پخش بارگیری و پخش می کند.
  • اگر player.nextVideo() در حالی که آخرین ویدیو در لیست پخش در حال مشاهده است فراخوانی شود، و لیست پخش برای پخش مداوم ( loop ) تنظیم شده باشد، پخش کننده اولین ویدیوی لیست را بارگیری و پخش می کند.

  • اگر player.nextVideo() در حالی که آخرین ویدیو در لیست پخش در حال مشاهده است فراخوانی شود و لیست پخش برای پخش مداوم تنظیم نشده باشد، پخش به پایان می رسد.

player. previousVideo ():Void
این عملکرد ویدیوی قبلی را در لیست پخش بارگیری و پخش می کند.
  • اگر player.previousVideo() در حالی که اولین ویدیو در لیست پخش در حال تماشا است فراخوانی شود، و لیست پخش به طور مداوم پخش شود ( loop )، پخش کننده آخرین ویدیوی لیست را بارگیری و پخش می کند.

  • اگر player.previousVideo() در حالی که اولین ویدیو در لیست پخش در حال مشاهده است فراخوانی شود و لیست پخش برای پخش مداوم تنظیم نشده باشد، پخش کننده اولین ویدیوی لیست پخش را از ابتدا مجدداً راه اندازی می کند.

player. playVideoAt (index:Number):Void
این عملکرد ویدیوی مشخص شده را در لیست پخش بارگیری و پخش می کند.
  • پارامتر index مورد نیاز نمایه ویدیویی را که می خواهید در لیست پخش پخش کنید مشخص می کند. این پارامتر از یک شاخص مبتنی بر صفر استفاده می کند، بنابراین مقدار 0 اولین ویدیو را در لیست مشخص می کند. اگر لیست پخش را به هم ریخته باشید، این عملکرد ویدیو را در موقعیت مشخص شده در لیست پخش به هم ریخته پخش می کند.

تغییر صدای پخش کننده

player. mute ():Void
پخش کننده را بی صدا می کند.
player. unMute ():Void
پخش کننده را لغو می کند.
player. isMuted ():Boolean
اگر پخش کننده بی صدا باشد true ، در غیر این صورت false برمی گرداند.
player. setVolume (volume:Number):Void
میزان صدا را تنظیم می کند. عدد صحیح بین 0 تا 100 را می پذیرد.
player. getVolume ():Number
حجم فعلی پخش کننده، عددی صحیح بین 0 تا 100 را برمی گرداند. توجه داشته باشید که getVolume() حجم صدا را برمی گرداند حتی اگر پخش کننده بی صدا باشد.

تنظیم اندازه پخش کننده

player.setSize(width:Number, height:Number):Object
اندازه <iframe> را که حاوی پخش کننده است بر حسب پیکسل تنظیم می کند.

تنظیم نرخ پخش

player. getPlaybackRate ():Number
این عملکرد نرخ پخش ویدیوی در حال پخش را بازیابی می کند. نرخ پخش پیش‌فرض 1 است که نشان می‌دهد ویدیو با سرعت عادی پخش می‌شود. نرخ پخش ممکن است شامل مقادیری مانند 0.25 ، 0.5 ، 1 ، 1.5 ، و 2 باشد.
player. setPlaybackRate (suggestedRate:Number):Void
این تابع نرخ پخش پیشنهادی را برای ویدیوی فعلی تنظیم می کند. اگر نرخ پخش تغییر کند، فقط برای ویدیویی که قبلاً نمایش داده شده یا در حال پخش است تغییر می کند. اگر نرخ پخش را برای یک ویدیوی نمایشی تنظیم کنید، زمانی که عملکرد playVideo فراخوانی می شود یا کاربر پخش را مستقیماً از طریق کنترل های پخش کننده شروع می کند، این نرخ همچنان فعال خواهد بود. علاوه بر این، فراخوانی توابع برای نشان دادن یا بارگیری ویدیوها یا لیست‌های پخش ( cueVideoById ، loadVideoById ، و غیره) نرخ پخش را به 1 بازنشانی می‌کند.

فراخوانی این عملکرد تضمین نمی کند که نرخ پخش واقعاً تغییر کند. با این حال، اگر نرخ پخش تغییر کند، رویداد onPlaybackRateChange فعال می‌شود و کد شما باید به رویداد پاسخ دهد نه اینکه تابع setPlaybackRate را فراخوانی کند.

روش getAvailablePlaybackRates نرخ پخش احتمالی ویدیوی در حال پخش را برمی گرداند. با این حال، اگر پارامتر suggestedRate را روی یک عدد صحیح یا مقدار شناور غیرپشتیبانی‌نشده تنظیم کنید، بازیکن آن مقدار را به نزدیک‌ترین مقدار پشتیبانی شده در جهت 1 گرد می‌کند.
player. getAvailablePlaybackRates ():Array
این تابع مجموعه نرخ‌های پخشی را که ویدیوی فعلی در آن موجود است را برمی‌گرداند. مقدار پیش فرض 1 است که نشان می دهد ویدیو با سرعت عادی پخش می شود.

این تابع آرایه ای از اعداد مرتب شده از کندترین به سریعترین سرعت پخش را برمی گرداند. حتی اگر پخش کننده از سرعت پخش متغیر پشتیبانی نکند، آرایه همیشه باید حداقل یک مقدار ( 1 ) داشته باشد.

تنظیم رفتار پخش برای لیست های پخش

player. setLoop (loopPlaylists:Boolean):Void

این عملکرد نشان می دهد که آیا پخش کننده ویدیو باید به طور مداوم یک لیست پخش را پخش کند یا اینکه پس از پایان آخرین ویدیو در لیست پخش، پخش آن متوقف شود. رفتار پیش فرض این است که لیست های پخش حلقه نمی شوند.

این تنظیم حتی اگر یک لیست پخش متفاوت را بارگیری یا نشانه گذاری کنید، ادامه خواهد داشت، به این معنی که اگر یک لیست پخش را بارگیری کنید، تابع setLoop را با مقدار true فراخوانی کنید و سپس لیست پخش دوم را بارگیری کنید، لیست پخش دوم نیز حلقه خواهد شد.

پارامتر loopPlaylists مورد نیاز رفتار حلقه را مشخص می کند.

  • اگر مقدار پارامتر true باشد، پخش کننده ویدیو به طور مداوم لیست های پخش را پخش می کند. پس از پخش آخرین ویدیو در یک لیست پخش، پخش کننده ویدیو به ابتدای لیست پخش برمی گردد و دوباره آن را پخش می کند.

  • اگر مقدار پارامتر false باشد، پس از اینکه پخش کننده ویدیو آخرین ویدیو را در یک لیست پخش پخش کرد، بازپخش پایان می یابد.

player. setShuffle (shufflePlaylist:Boolean):Void

این عملکرد نشان می دهد که آیا ویدیوهای یک لیست پخش باید به هم ریخته شوند تا به ترتیبی متفاوت از ترتیبی که سازنده لیست پخش تعیین کرده پخش شوند. اگر یک لیست پخش را بعد از شروع پخش آن به هم بزنید، تا زمانی که ویدیوی در حال پخش به پخش ادامه می‌دهد، فهرست دوباره مرتب می‌شود. سپس ویدیوی بعدی که پخش می‌شود بر اساس فهرستی که مرتب شده است انتخاب می‌شود.

اگر لیست پخش دیگری را بارگیری کنید یا علامت بزنید، این تنظیم ادامه نخواهد داشت، به این معنی که اگر یک لیست پخش را بارگیری کنید، تابع setShuffle را فراخوانی کنید و سپس لیست پخش دوم را بارگیری کنید، لیست پخش دوم به هم ریخته نخواهد شد.

پارامتر shufflePlaylist مورد نیاز نشان می دهد که آیا YouTube باید لیست پخش را به هم بزند یا خیر.

  • اگر مقدار پارامتر true باشد، YouTube ترتیب لیست پخش را تغییر می دهد. اگر به این تابع دستور دهید تا لیست پخشی را که قبلاً به هم ریخته شده است به هم بزند، YouTube دوباره ترتیب را به هم می‌زند.

  • اگر مقدار پارامتر false باشد، YouTube ترتیب لیست پخش را به ترتیب اصلی خود تغییر خواهد داد.

وضعیت پخش

player. getVideoLoadedFraction ():Float
عددی بین 0 و 1 را برمی‌گرداند که درصد ویدیویی را که پخش‌کننده به‌عنوان بافر نشان می‌دهد، مشخص می‌کند. این روش عدد قابل اعتمادتری را نسبت به متدهای getVideoBytesLoaded و getVideoBytesTotal که اکنون منسوخ شده اند، برمی گرداند.
player.getPlayerState():Number
وضعیت بازیکن را برمی‌گرداند. مقادیر ممکن عبارتند از:
  • -1 - شروع نشده است
  • 0 - پایان یافت
  • 1 - بازی کردن
  • 2 - مکث
  • 3 بافر کردن
  • 5 - تصویری cued
player. getCurrentTime ():Number
زمان سپری شده از زمان شروع پخش ویدیو را بر حسب ثانیه برمی گرداند.
player. getVideoStartBytes ():Number
از 31 اکتبر 2012 منسوخ شده است. تعداد بایت هایی را که فایل ویدیویی از آنها بارگیری شده است را برمی گرداند. (این روش اکنون همیشه مقدار 0 را برمی گرداند.) سناریوی مثال: کاربر به دنبال نقطه ای است که هنوز بارگیری نشده است، و بازیکن درخواست جدیدی برای پخش بخشی از ویدیویی که هنوز بارگذاری نشده است ارائه می دهد.
player. getVideoBytesLoaded ():Number
از 18 ژوئیه 2012 منسوخ شده است . در عوض، از روش getVideoLoadedFraction برای تعیین درصد ویدیویی که بافر شده است استفاده کنید.

این روش مقداری بین 0 تا 1000 برمی‌گرداند که تقریباً مقدار ویدیویی که بارگذاری شده است را نشان می‌دهد. با تقسیم مقدار getVideoBytesLoaded بر مقدار getVideoBytesTotal می‌توانید کسری از ویدیوی بارگذاری شده را محاسبه کنید.
player. getVideoBytesTotal ():Number
از 18 ژوئیه 2012 منسوخ شده است. در عوض، از روش getVideoLoadedFraction برای تعیین درصد ویدیویی که بافر شده است استفاده کنید.

اندازه ویدیوی بارگیری/در حال پخش یا تقریبی اندازه ویدیو را بر حسب بایت برمی‌گرداند.

این روش همیشه مقدار 1000 را برمی گرداند. با تقسیم مقدار getVideoBytesLoaded بر مقدار getVideoBytesTotal می‌توانید کسری از ویدیوی بارگذاری شده را محاسبه کنید.

بازیابی اطلاعات ویدیویی

player. getDuration ():Number
مدت زمان ویدیوی در حال پخش را بر حسب ثانیه برمی‌گرداند. توجه داشته باشید که getDuration() تا زمانی که ابرداده ویدیو بارگیری شود 0 برمی گردد، که معمولاً درست پس از شروع پخش ویدیو اتفاق می افتد.

اگر ویدیوی در حال پخش یک رویداد زنده باشد، تابع getDuration() زمان سپری شده از شروع پخش زنده ویدیو را برمی گرداند. به طور خاص، این مدت زمانی است که ویدیو بدون تنظیم مجدد یا قطع شده است. علاوه بر این، این مدت معمولاً بیشتر از زمان واقعی رویداد است زیرا پخش جریانی ممکن است قبل از زمان شروع رویداد شروع شود.
player. getVideoUrl ():String
URL YouTube.com را برای ویدیوی بارگیری/در حال پخش برمی‌گرداند.
player. getVideoEmbedCode ():String
کد جاسازی شده را برای ویدیوی بارگیری/در حال پخش برمی‌گرداند.

بازیابی اطلاعات لیست پخش

player. getPlaylist ():Array
این تابع آرایه ای از شناسه های ویدیویی موجود در لیست پخش را همانطور که در حال حاضر مرتب شده اند، برمی گرداند. By default, this function will return video IDs in the order designated by the playlist owner. However, if you have called the setShuffle function to shuffle the playlist order, then the getPlaylist() function's return value will reflect the shuffled order.
player. getPlaylistIndex ():Number
This function returns the index of the playlist video that is currently playing.
  • If you have not shuffled the playlist, the return value will identify the position where the playlist creator placed the video. The return value uses a zero-based index, so a value of 0 identifies the first video in the playlist.

  • If you have shuffled the playlist, the return value will identify the video's order within the shuffled playlist.

Adding or removing an event listener

player. addEventListener (event:String, listener:String):Void
Adds a listener function for the specified event . The Events section below identifies the different events that the player might fire. The listener is a string that specifies the function that will execute when the specified event fires.
player. removeEventListener (event:String, listener:String):Void
Removes a listener function for the specified event . The listener is a string that identifies the function that will no longer execute when the specified event fires.

Accessing and modifying DOM nodes

player. getIframe ():Object
This method returns the DOM node for the embedded <iframe> .
player. destroy ():Void
Removes the <iframe> containing the player.

Events

The API fires events to notify your application of changes to the embedded player. As noted in the previous section, you can subscribe to events by adding an event listener when constructing the YT.Player object , and you can also use the addEventListener function.

The API will pass an event object as the sole argument to each of those functions. The event object has the following properties:

  • The event's target identifies the video player that corresponds to the event.
  • The event's data specifies a value relevant to the event. Note that the onReady event does not specify a data property.

The following list defines the events that the API fires:

onReady
This event fires whenever a player has finished loading and is ready to begin receiving API calls. Your application should implement this function if you want to automatically execute certain operations, such as playing the video or displaying information about the video, as soon as the player is ready.

The example below shows a sample function for handling this event. The event object that the API passes to the function has a target property, which identifies the player. The function retrieves the embed code for the currently loaded video, starts to play the video, and displays the embed code in the page element that has an id value of embed-code .
function onPlayerReady(event) {
  var embedCode = event.target.getVideoEmbedCode();
  event.target.playVideo();
  if (document.getElementById('embed-code')) {
    document.getElementById('embed-code').innerHTML = embedCode;
  }
}
onStateChange
This event fires whenever the player's state changes. The data property of the event object that the API passes to your event listener function will specify an integer that corresponds to the new player state. Possible values are:

  • -1 (unstarted)
  • 0 (ended)
  • 1 (playing)
  • 2 (paused)
  • 3 (buffering)
  • 5 (video cued).

When the player first loads a video, it will broadcast an unstarted ( -1 ) event. When a video is cued and ready to play, the player will broadcast a video cued ( 5 ) event. In your code, you can specify the integer values or you can use one of the following namespaced variables:

  • YT.PlayerState.ENDED
  • YT.PlayerState.PLAYING
  • YT.PlayerState.PAUSED
  • YT.PlayerState.BUFFERING
  • YT.PlayerState.CUED

onPlaybackQualityChange
This event fires whenever the video playback quality changes. It might signal a change in the viewer's playback environment. See the YouTube Help Center for more information about factors that affect playback conditions or that might cause the event to fire.

The data property value of the event object that the API passes to the event listener function will be a string that identifies the new playback quality. Possible values are:

  • small
  • medium
  • large
  • hd720
  • hd1080
  • highres

onPlaybackRateChange
This event fires whenever the video playback rate changes. For example, if you call the setPlaybackRate(suggestedRate) function, this event will fire if the playback rate actually changes. Your application should respond to the event and should not assume that the playback rate will automatically change when the setPlaybackRate(suggestedRate) function is called. Similarly, your code should not assume that the video playback rate will only change as a result of an explicit call to setPlaybackRate .

The data property value of the event object that the API passes to the event listener function will be a number that identifies the new playback rate. The getAvailablePlaybackRates method returns a list of the valid playback rates for the currently cued or playing video.
onError
This event fires if an error occurs in the player. The API will pass an event object to the event listener function. That object's data property will specify an integer that identifies the type of error that occurred. Possible values are:

  • 2 – The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.
  • 5 – The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.
  • 100 – The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.
  • 101 – The owner of the requested video does not allow it to be played in embedded players.
  • 150 – This error is the same as 101 . It's just a 101 error in disguise!
onApiChange
This event is fired to indicate that the player has loaded (or unloaded) a module with exposed API methods. Your application can listen for this event and then poll the player to determine which options are exposed for the recently loaded module. Your application can then retrieve or update the existing settings for those options.

The following command retrieves an array of module names for which you can set player options:
player.getOptions();
Currently, the only module that you can set options for is the captions module, which handles closed captioning in the player. Upon receiving an onApiChange event, your application can use the following command to determine which options can be set for the captions module:
player.getOptions('captions');
By polling the player with this command, you can confirm that the options you want to access are, indeed, accessible. The following commands retrieve and update module options:
Retrieving an option:
player.getOption(module, option);

Setting an option
player.setOption(module, option, value);
The table below lists the options that the API supports:

Module Option Description
captionsfontSize This option adjusts the font size of the captions displayed in the player.

Valid values are -1 , 0 , 1 , 2 , and 3 . The default size is 0 , and the smallest size is -1 . Setting this option to an integer below -1 will cause the smallest caption size to display, while setting this option to an integer above 3 will cause the largest caption size to display.
captionsreload This option reloads the closed caption data for the video that is playing. The value will be null if you retrieve the option's value. Set the value to true to reload the closed caption data.

Mobile Considerations

Autoplay and Scripted Playback

The HTML5 <video> element, in certain mobile browsers (such as Chrome and Safari), only allows playback to take place if it's initiated by a user interaction (such as tapping on the player). Here's an excerpt from Apple's documentation :

"Warning: To prevent unsolicited downloads over cellular networks at the user's expense, embedded media cannot be played automatically in Safari on iOS — the user always initiates playback."

Due to this restriction, functions and parameters such as autoplay , playVideo() , loadVideoById() won't work in all mobile environments.

مثال ها

Creating YT.Player objects

  • Example 1: Use API with existing <iframe>

    In this example, an <iframe> element on the page already defines the player with which the API will be used. Note that either the player's src URL must set the enablejsapi parameter to 1 or the <iframe> element's enablejsapi attribute must be set to true .

    The onPlayerReady function changes the color of the border around the player to orange when the player is ready. The onPlayerStateChange function then changes the color of the border around the player based on the current player status. For example, the color is green when the player is playing, red when paused, blue when buffering, and so forth.

    This example uses the following code:

    <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>
    
  • Example 2: Loud playback

    This example creates a 1280px by 720px video player. The event listener for the onReady event then calls the setVolume function to adjust the volume to the highest setting.

    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();
    }
    
  • Example 3: This example sets player parameters to automatically play the video when it loads and to hide the video player's controls. It also adds event listeners for several events that the API broadcasts.

    function onYouTubeIframeAPIReady() {
      var player;
      player = new YT.Player('player', {
        videoId: 'M7lc1UVf-VE',
        playerVars: { 'autoplay': 1, 'controls': 0 },
        events: {
          'onReady': onPlayerReady,
          'onStateChange': onPlayerStateChange,
          'onError': onPlayerError
        }
      });
    }

Controlling 360° videos

This example uses the following code:

<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>

Revision history

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 <iframe> element.

January 6, 2016

The clearVideo function has been deprecated and removed from the documentation. The function no longer has any effect in the YouTube player.

December 18, 2015

European Union (EU) laws require that certain disclosures must be given to and consents obtained from end users in the EU. Therefore, for end users in the European Union, you must comply with the EU User Consent Policy . We have added a notice of this requirement in our YouTube API Terms of Service .

April 28, 2014

This update contains the following changes:

March 25, 2014

This update contains the following changes:

  • The Requirements section has been updated to note that embedded players must have a viewport that is at least 200px by 200px. If a player displays controls, it must be large enough to fully display the controls without shrinking the viewport below the minimum size. We recommend 16:9 players be at least 480 pixels wide and 270 pixels tall.

July 23, 2013

This update contains the following changes:

  • The Overview now includes a video of a 2011 Google I/O presentation that discusses the iframe player.

October 31, 2012

This update contains the following changes:

  • The Queueing functions section has been updated to explain that you can use either argument syntax or object syntax to call all of those functions. Note that the API may support additional functionality in object syntax that the argument syntax does not support.

    In addition, the descriptions and examples for each of the video queueing functions have been updated to reflect the newly added support for object syntax. (The API's playlist queueing functions already supported object syntax.)

  • When called using object syntax, each of the video queueing functions supports an endSeconds property, which accepts a float/integer and specifies the time when the video should stop playing when playVideo() is called.

  • The getVideoStartBytes method has been deprecated. The method now always returns a value of 0 .

August 22, 2012

This update contains the following changes:

  • The example in the Loading a video player section that demonstrates how to manually create the <iframe> tag has been updated to include a closing </iframe> tag since the onYouTubeIframeAPIReady function is only called if the closing </iframe> 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 <iframe> that contains the player and the destroy() method removes the <iframe> .

June 6, 2012

This update contains the following changes:

  • We have removed the experimental status from the IFrame Player API.

  • The Loading a video player section has been updated to point out that when inserting the <iframe> element that will contain the YouTube player, the IFrame API replaces the element specified in the constructor for the YouTube player. This documentation change does not reflect a change in the API and is intended solely to clarify existing behavior.

    In addition, that section now notes that the insertion of the <iframe> element could affect the layout of your page if the element being replaced has a different display style than the inserted <iframe> element. By default, an <iframe> displays as an inline-block element.

March 30, 2012

This update contains the following changes:

  • The Operations section has been updated to explain that the IFrame API supports a new method, getIframe() , which returns the DOM node for the IFrame embed.

March 26, 2012

This update contains the following changes:

  • The Requirements section has been updated to note the minimum player size.