API проигрывателя IFrame позволяет встроить видеоплеер YouTube на свой веб-сайт и управлять им с помощью JavaScript.
Используя функции JavaScript API, вы можете поставить видео в очередь для воспроизведения; воспроизводить, приостанавливать или останавливать эти видео; отрегулировать громкость плеера; или получить информацию о воспроизводимом видео. Вы также можете добавить прослушиватели событий, которые будут выполняться в ответ на определенные события игрока, например изменение состояния игрока.
В этом руководстве объясняется, как использовать API IFrame. Он определяет различные типы событий, которые может отправлять API, и объясняет, как написать прослушиватели событий для реагирования на эти события. В нем также подробно описаны различные функции JavaScript, которые вы можете вызывать для управления видеоплеером, а также параметры проигрывателя, которые вы можете использовать для дальнейшей настройки проигрывателя.
Требования
Браузер пользователя должен поддерживать функцию 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, также должна реализовывать следующую функцию JavaScript:
onYouTubeIframeAPIReady
— API вызовет эту функцию, когда страница завершит загрузку JavaScript для 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>
В следующем списке представлены более подробные сведения о приведенном выше образце:
Тег
<div>
в этом разделе определяет место на странице, где API IFrame разместит видеопроигрыватель. Конструктор объекта проигрывателя, описанный в разделе «Загрузка видеопроигрывателя» , идентифицирует тег<div>
по егоid
, чтобы гарантировать, что API разместит<iframe>
в правильном месте. В частности, API IFrame заменит тег<div>
тегом<iframe>
.В качестве альтернативы вы также можете разместить элемент
<iframe>
непосредственно на странице. В разделе «Загрузка видеоплеера» объясняется, как это сделать.Код в этом разделе загружает код JavaScript API IFrame Player. В примере используется модификация DOM для загрузки кода API, чтобы обеспечить асинхронное получение кода. (
async
атрибут тега<script>
, который также обеспечивает асинхронную загрузку, пока не поддерживается во всех современных браузерах, как описано в этом ответе на Stack Overflow .Функция
onYouTubeIframeAPIReady
выполнится сразу после загрузки кода API проигрывателя. Эта часть кода определяет глобальную переменнуюplayer
, которая ссылается на встраиваемый видеоплеер, а затем функция создает объект видеоплеера.Функция
onPlayerReady
будет выполняться при возникновении событияonReady
. В этом примере функция указывает, что когда видеоплеер будет готов, он должен начать воспроизведение.API вызовет функцию
onPlayerStateChange
при изменении состояния проигрывателя, что может указывать на то, что проигрыватель играет, поставлен на паузу, закончил и т. д. Функция указывает, что когда состояние проигрывателя равно1
(воспроизведение), проигрыватель должен воспроизводить видео в течение шести секунд, а затем вызвать функциюstopVideo
, чтобы остановить видео.
Загрузка видеоплеера
После загрузки кода JavaScript 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 } }); }
Конструктор видеоплеера указывает следующие параметры:
Первый параметр указывает либо элемент DOM, либо
id
элемента HTML, в который API вставит тег<iframe>
, содержащий проигрыватель.API IFrame заменит указанный элемент элементом
<iframe>
, содержащим проигрыватель. Это может повлиять на макет вашей страницы, если заменяемый элемент имеет стиль отображения, отличный от вставленного элемента<iframe>
. По умолчанию<iframe>
отображается как элементinline-block
.- Второй параметр — это объект, определяющий параметры игрока. Объект содержит следующие свойства:
-
width
(число) – ширина видеоплеера. Значение по умолчанию —640
. -
height
(число) – высота видеоплеера. Значение по умолчанию —390
. -
videoId
(строка) – идентификатор видео YouTube, который идентифицирует видео, которое плеер будет загружать. -
playerVars
(объект) – свойства объекта определяют параметры проигрывателя , которые можно использовать для настройки проигрывателя. -
events
(объект). Свойства объекта определяют события, которые запускает API, и функции (прослушиватели событий), которые API будет вызывать при возникновении этих событий. В этом примере конструктор указывает, что функцияonPlayerReady
будет выполняться при возникновении событияonReady
и что функцияonPlayerStateChange
будет выполняться при возникновении событияonStateChange
.
-
Как упоминалось в разделе « Начало работы », вместо написания пустого элемента <div>
на вашей странице, который код JavaScript API проигрывателя затем заменит элементом <iframe>
, вы можете создать тег <iframe>
самостоятельно. Первый пример в разделе «Примеры» показывает, как это сделать.
<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
. В качестве дополнительной меры безопасности вам также следует включить в URL-адрес параметр origin
, указав схему URL-адреса ( http://
или https://
) и полный домен вашей хост-страницы в качестве значения параметра. Хотя origin
не является обязательным, в том числе оно защищает от вредоносного стороннего JavaScript, внедренного на вашу страницу и перехвата контроля над вашим проигрывателем YouTube.
Другие примеры создания объектов видеопроигрывателя см. в разделе «Примеры» .
Операции
Чтобы вызвать методы 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
Эта функция загружает миниатюру указанного видео и подготавливает проигрыватель к воспроизведению видео. Проигрыватель не запрашивает FLV до тех пор, пока не будет вызвана
playVideo()
илиseekTo()
.- Обязательный параметр
videoId
указывает идентификатор видео YouTube для воспроизводимого видео. В API данных YouTube свойствоid
video
указывает идентификатор. - Необязательный параметр
startSeconds
принимает число с плавающей запятой или целое число и указывает время, с которого видео должно начать воспроизведение при вызовеplayVideo()
. Если вы укажете значениеstartSeconds
, а затем вызоветеseekTo()
, то игрок начнет играть со времени, указанного в вызовеseekTo()
. Когда видео будет воспроизведено и готово к воспроизведению, проигрыватель будет транслировать событиеvideo cued
(5
). - Необязательный параметр
endSeconds
, который поддерживается только в синтаксисе объекта, принимает число с плавающей запятой или целое число и указывает время, когда видео должно прекратить воспроизведение при вызовеplayVideo()
. Если вы укажете значениеendSeconds
, а затем вызоветеseekTo()
, значениеendSeconds
больше не будет действовать.
loadVideoById
Синтаксис аргумента
player.loadVideoById(videoId:String, startSeconds:Number):Void
Синтаксис объекта
player.loadVideoById({videoId:String, startSeconds:Number, endSeconds:Number}):Void
Эта функция загружает и воспроизводит указанное видео.
- Обязательный параметр
videoId
указывает идентификатор видео YouTube для воспроизводимого видео. В API данных YouTube свойствоid
video
указывает идентификатор. - Необязательный параметр
startSeconds
принимает число с плавающей запятой или целое число. Если он указан, то видео начнется с ближайшего к указанному времени ключевого кадра. - Необязательный параметр
endSeconds
принимает число с плавающей запятой или целое число. Если он указан, то воспроизведение видео прекратится в указанное время.
cueVideoByUrl
Синтаксис аргумента
player.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void
Синтаксис объекта
player.cueVideoByUrl({mediaContentUrl:String, startSeconds:Number, endSeconds:Number}):Void
Эта функция загружает миниатюру указанного видео и подготавливает проигрыватель к воспроизведению видео. Проигрыватель не запрашивает FLV до тех пор, пока не будет вызвана
playVideo()
илиseekTo()
.- Обязательный параметр
mediaContentUrl
указывает полный URL-адрес проигрывателя YouTube в форматеhttp://www.youtube.com/v/VIDEO_ID?version=3
. - Необязательный параметр
startSeconds
принимает число с плавающей запятой или целое число и указывает время, с которого видео должно начать воспроизведение при вызовеplayVideo()
. Если вы укажетеstartSeconds
, а затем вызоветеseekTo()
, то игрок начнет играть со времени, указанного в вызовеseekTo()
. Когда видео будет воспроизведено и готово к воспроизведению, проигрыватель будет транслировать событиеvideo cued
(5). - Необязательный параметр
endSeconds
, который поддерживается только в синтаксисе объекта, принимает число с плавающей запятой или целое число и указывает время, когда видео должно прекратить воспроизведение при вызове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
принимает число с плавающей запятой или целое число и указывает время, с которого должно начаться воспроизведение видео. Если указаноstartSeconds
(число может быть числом с плавающей запятой), видео начнется с ближайшего ключевого кадра к указанному времени. - Необязательный параметр
endSeconds
, который поддерживается только в синтаксисе объекта, принимает число с плавающей запятой или целое число и указывает время, когда видео должно прекратить воспроизведение.
Функции очередей для списков
Функции cuePlaylist
и loadPlaylist
позволяют загружать и воспроизводить список воспроизведения. Если вы используете объектный синтаксис для вызова этих функций, вы также можете поставить в очередь (или загрузить) список загруженных пользователем видео.
Поскольку функции работают по-разному в зависимости от того, вызываются ли они с использованием синтаксиса аргумента или синтаксиса объекта, оба метода вызова описаны ниже.
-
cuePlaylist
Синтаксис аргумента
Ставит в очередь указанный список воспроизведения. Когда плейлист готов к воспроизведению, проигрыватель транслирует событиеplayer.cuePlaylist(playlist:String|Array, index:Number, startSeconds:Number):Void
video cued
(5
).Обязательный параметр
playlist
указывает массив идентификаторов видео YouTube. В API данных YouTube свойствоid
video
идентифицирует идентификатор этого видео.Необязательный параметр
index
указывает индекс первого видео в списке воспроизведения, которое будет воспроизводиться. В параметре используется индекс, начинающийся с нуля, а значение параметра по умолчанию —0
, поэтому поведение по умолчанию — загрузка и воспроизведение первого видео в списке воспроизведения.Необязательный параметр
startSeconds
принимает число с плавающей запятой или целое число и указывает время, с которого должно начаться воспроизведение первого видео в списке воспроизведения при вызове функции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
указывает идентификатор списка воспроизведения или массив идентификаторов видео. В API данных YouTube свойствоid
ресурсаplaylist
идентифицирует идентификатор списка воспроизведения, а свойствоid
video
указывает идентификатор видео. - Если значение свойства
listType
—user_uploads
, то свойствоlist
идентифицирует пользователя, чьи загруженные видео будут возвращены. - Если значением свойства
listType
являетсяsearch
, то свойствоlist
определяет поисковый запрос. Примечание. Эта функция устарела и больше не будет поддерживаться с15 ноября 2020 г.
- Если значение свойства
Необязательное свойство
index
указывает индекс первого видео в списке, которое будет воспроизводиться. В параметре используется индекс, начинающийся с нуля, а значение параметра по умолчанию —0
, поэтому поведение по умолчанию — загрузка и воспроизведение первого видео в списке.Необязательное свойство
startSeconds
принимает число с плавающей запятой или целое число и указывает время, с которого должно начаться воспроизведение первого видео в списке при вызове функцииplayVideo()
. Если вы укажете значениеstartSeconds
, а затем вызоветеseekTo()
, то игрок начнет играть со времени, указанного в вызовеseekTo()
. Если вы выберете список, а затем вызовете функциюplayVideoAt()
, плеер начнет воспроизведение с начала указанного видео.
-
loadPlaylist
Синтаксис аргумента
Эта функция загружает указанный список воспроизведения и воспроизводит его.player.loadPlaylist(playlist:String|Array, index:Number, startSeconds:Number):Void
Обязательный параметр
playlist
указывает массив идентификаторов видео YouTube. В API данных YouTube свойствоid
video
указывает идентификатор видео.Необязательный параметр
index
указывает индекс первого видео в списке воспроизведения, которое будет воспроизводиться. В параметре используется индекс, начинающийся с нуля, а значение параметра по умолчанию —0
, поэтому поведение по умолчанию — загрузка и воспроизведение первого видео в списке воспроизведения.Необязательный параметр
startSeconds
принимает число с плавающей запятой или целое число и указывает время, с которого должно начаться воспроизведение первого видео в списке воспроизведения.
Синтаксис объекта
Эта функция загружает указанный список и воспроизводит его. Список может представлять собой список воспроизведения или канал загруженных пользователем видео. Возможность загрузки списка результатов поиска устарела и больше не будет поддерживаться с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
указывает идентификатор списка воспроизведения или массив идентификаторов видео. В API данных YouTube свойствоid
ресурсаplaylist
указывает идентификатор списка воспроизведения, а свойствоid
video
указывает идентификатор видео. - Если значение свойства
listType
—user_uploads
, то свойствоlist
идентифицирует пользователя, чьи загруженные видео будут возвращены. - Если значением свойства
listType
являетсяsearch
, то свойствоlist
определяет поисковый запрос. Примечание. Эта функция устарела и больше не будет поддерживаться с15 ноября 2020 г.
- Если значение свойства
Необязательное свойство
index
указывает индекс первого видео в списке, которое будет воспроизводиться. В параметре используется индекс, начинающийся с нуля, а значение параметра по умолчанию —0
, поэтому поведение по умолчанию — загрузка и воспроизведение первого видео в списке.Необязательное свойство
startSeconds
принимает число с плавающей запятой или целое число и указывает время, с которого должно начаться воспроизведение первого видео в списке.
Элементы управления воспроизведением и настройки плеера
Воспроизведение видео
-
player. playVideo ():Void
- Воспроизводит текущее загруженное видео. Окончательным состоянием игрока после выполнения этой функции будет
playing
(1).
Примечание. Воспроизведение засчитывается в официальное количество просмотров видео только в том случае, если оно инициируется с помощью встроенной кнопки воспроизведения в плеере.
-
player. pauseVideo ():Void
- Приостанавливает воспроизводимое в данный момент видео. Окончательное состояние игрока после выполнения этой функции будет
paused
(2
), если только игрок не находится вended
состоянии (0
) при вызове функции, и в этом случае состояние игрока не изменится.
-
player. stopVideo ():Void
- Останавливает и отменяет загрузку текущего видео. Эту функцию следует зарезервировать для редких ситуаций, когда вы знаете, что пользователь не будет смотреть дополнительное видео в плеере. Если вы намерены приостановить видео, вам следует просто вызвать функцию
pauseVideo
. Если вы хотите изменить видео, воспроизводимое проигрывателем, вы можете вызвать одну из функций организации очереди без предварительного вызоваstopVideo
.
Важно: в отличие от функцииpauseVideo
, которая оставляет проигрыватель в состоянииpaused
(2
), функцияstopVideo
может перевести проигрыватель в любое невоспроизводимое состояние, включаяended
(0
),paused
(2
),video 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°. Значение увеличивается при вращении представления по часовой стрелке и уменьшается при вращении представления против часовой стрелки.
Обратите внимание, что встроенный проигрыватель не имеет пользовательского интерфейса для настройки угла обзора. Крен можно регулировать любым из этих взаимоисключающих способов:- Используйте датчик ориентации в мобильном браузере, чтобы обеспечить поворот изображения. Если датчик ориентации включен, функция
getSphericalProperties
всегда возвращает0
в качестве значения свойстваroll
. - Если датчик ориентации отключен, установите для рулона ненулевое значение с помощью этого API.
fov
Число в диапазоне [30, 120], которое представляет поле зрения в градусах, измеренное вдоль длинного края области просмотра. Более короткий край автоматически настраивается пропорционально соотношению сторон изображения.
Значение по умолчанию — 100 градусов. Уменьшение значения аналогично увеличению видеоконтента, а увеличение значения — уменьшению масштаба. Это значение можно настроить либо с помощью API, либо с помощью колеса мыши, когда видео находится в полноэкранном режиме.
-
player. setSphericalProperties (properties:Object):Void
- Устанавливает ориентацию видео для воспроизведения видео в формате 360°. (Если текущее видео не сферическое, метод не работает независимо от входных данных.)
Представление игрока отвечает на вызовы этого метода обновлением, чтобы отразить значения любых известных свойств в объектеproperties
. В представлении сохраняются значения для любых других известных свойств, не включенных в этот объект.
Кроме того:- Если объект содержит неизвестные и/или неожиданные свойства, игрок их игнорирует.
- Как отмечалось в начале этого раздела, воспроизведение видео в формате 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
– видео-подсказка
-
-
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
- Эта функция возвращает массив идентификаторов видео в списке воспроизведения в том виде, в котором они в данный момент упорядочены. По умолчанию эта функция возвращает идентификаторы видео в порядке, указанном владельцем плейлиста. Однако если вы вызвали функцию
setShuffle
для перетасовки порядка воспроизведения, то возвращаемое значение функцииgetPlaylist()
будет отражать перетасованный порядок.
-
player. getPlaylistIndex ():Number
- Эта функция возвращает индекс видео плейлиста, которое в настоящее время играет.
Если вы не перетасовали список воспроизведения, возвратное значение определит позицию, в которой создатель плейлиста разместил видео. Возвратное значение использует индекс на основе нуля, поэтому значение
0
идентифицирует первое видео в списке воспроизведения.Если вы перетасовали список воспроизведения, возвращаемое значение определит заказ видео в перетасованном списке воспроизведения.
Добавление или удаление слушателя событий
-
player. addEventListener (event:String, listener:String):Void
- Добавляет функцию слушателя для указанного
event
. Раздел событий ниже определяет различные события, которые игрок может сбросить. Слушатель - это строка, которая указывает функцию, которая будет выполняться при стрельбе указанного события.
-
player. removeEventListener (event:String, listener:String):Void
- Удаляет функцию слушателя для указанного
event
.listener
- это строка, которая идентифицирует функцию, которая больше не будет выполняться, когда указанное событие запускается.
Доступ и изменение узлов DOM
-
player. getIframe ():Object
- Этот метод возвращает узел DOM для встроенного
<iframe>
.
-
player. destroy ():Void
- Удаляет
<iframe>
, содержащий игрока.
События
API запускает события, чтобы уведомить ваше применение изменений в встроенного игрока. Как отмечалось в предыдущем разделе, вы можете подписаться на события, добавив слушатель событий при построении объекта YT.Player
, а также вы можете использовать функцию addEventListener
.
API будет передавать объект события в качестве единственного аргумента каждой из этих функций. Объект события обладает следующими свойствами:
-
target
события идентифицирует видеоплеер, который соответствует событию. -
data
события указывают значение, относящееся к событию. Обратите внимание, что событияonReady
иonAutoplayBlocked
не указывают свойствоdata
.
Следующий список определяет события, которые запускает API:
-
onReady
- Это событие запускается всякий раз, когда игрок заканчивал загрузку, и готово начать получать вызовы API. Ваше приложение должно реализовать эту функцию, если вы хотите автоматически выполнить определенные операции, такие как воспроизведение видео или отображение информации о видео, как только игрок будет готов.
В примере ниже показан образец функции для обработки этого события. Объект события, который API передает функции, имеетtarget
свойство, которое идентифицирует игрока. Функция извлекает код Embed для загруженного в настоящее время видео, начинает воспроизводить видео и отображает код Embed в элементе страницы, который имеет значениеid
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
- Это событие запускается всякий раз, когда изменяется состояние игрока. Свойство
data
объекта события, которое API передает функции слушателя вашего события, будет указано целое число, которое соответствует новому состоянию игрока. Возможные значения:-
-1
(нестабильно) -
0
(закончилось) -
1
(игра) -
2
(приостановлен) -
3
(буферизация) -
5
(видеосвязан).
unstarted
(-1
) событие. Когда видео будет подготовлено и готово к воспроизведению, игрок будет транслироватьvideo cued
(5
) событие. В вашем коде вы можете указать целочисленные значения, или вы можете использовать одну из следующих переменных с именами:-
YT.PlayerState.ENDED
-
YT.PlayerState.PLAYING
-
YT.PlayerState.PAUSED
-
YT.PlayerState.BUFFERING
-
YT.PlayerState.CUED
-
-
onPlaybackQualityChange
- Это событие запускается всякий раз, когда меняется качество воспроизведения видео. Это может сигнализировать об изменении в среде воспроизведения зрителя. См. Справочный центр YouTube для получения дополнительной информации о факторах, которые влияют на условия воспроизведения или которые могут привести к стрельбе.
Значение свойстваdata
объекта события, которое API передает функции слушателя событий, будет строкой, которая идентифицирует новое качество воспроизведения. Возможные значения:-
small
-
medium
-
large
-
hd720
-
hd1080
-
highres
-
-
onPlaybackRateChange
- Это событие запускается всякий раз, когда меняется скорость воспроизведения видео. Например, если вы называете функцию
setPlaybackRate(suggestedRate)
, это событие будет стрелять, если скорость воспроизведения действительно изменится. Ваше приложение должно отвечать на событие и не должно предполагать, что скорость воспроизведения будет автоматически изменяться при вызове функцииsetPlaybackRate(suggestedRate)
. Аналогичным образом, ваш код не должен предполагать, что скорость воспроизведения видео изменится только в результате явного вызоваsetPlaybackRate
.
Значение свойстваdata
объекта события, которое API передает функции слушателя событий, будет числом, которое идентифицирует новый уровень воспроизведения. МетодgetAvailablePlaybackRates
возвращает список действительных ставок воспроизведения для в настоящее время или воспроизводить видео.
-
onError
- Это событие запускается, если у игрока возникает ошибка. API передаст объект
event
функции слушателя событий. Свойствоdata
этого объекта будет указывать целое число, которое идентифицирует тип возникновенной ошибки. Возможные значения:-
2
- Запрос содержит неверное значение параметра. Например, эта ошибка возникает, если вы указываете идентификатор видео, который не имеет 11 символов, или если идентификатор видео содержит неверные символы, такие как восклицательные очки или звездочки. -
5
- Запрашиваемый контент не может быть воспроизведен в игроке HTML5 или другой ошибке, связанной с игроком HTML5. -
100
- запрошенное видео не было найдено. Эта ошибка возникает, когда видео было удалено (по любой причине) или была отмечена как частное. -
101
- Владелец запрошенного видео не позволяет воспроизводить его во встроенных игроках. -
150
- Эта ошибка такая же, как101
. Это просто замаскированная ошибка101
!
-
-
onApiChange
- Это событие запускается, чтобы указать, что игрок загрузил (или разгрузил) модуль с открытыми методами API. Ваше приложение может прослушать это событие, а затем опросить игрока, чтобы определить, какие варианты выставлены для недавно загруженного модуля. Затем ваше приложение может получить или обновить существующие настройки для этих параметров.
Следующая команда получает массив имен модулей, для которых вы можете установить параметры игрока: В настоящее время единственный модуль, для которого вы можете установить параметры, - это модульplayer.getOptions();
captions
, который обрабатывает закрытые подписи у игрока. После получения событияonApiChange
, ваше приложение может использовать следующую команду, чтобы определить, какие параметры можно установить для модуляcaptions
: Опротив игрока этой командой, вы можете подтвердить, что варианты, к которым вы хотите получить доступ, действительно доступны. Следующие команды извлечены и обновлять параметры модуля:player.getOptions('captions');
В таблице ниже перечислены параметры, которые поддерживает API:Retrieving an option: player.getOption(module, option); Setting an option player.setOption(module, option, value);
Модуль Вариант Описание captions fontSize Эта опция настраивает размер шрифта подписей, отображаемых в игроке.
Допустимые значения составляют-1
,0
,1
,2
и3
. Размер по умолчанию равен0
, а наименьший размер-1
. Установка этой опции на целое число ниже-1
приведет к отображению наименьшего размера заголовка, в то время как установка этой опции на целое число выше3
приведет к отображению наибольшего размера заголовка.captions reload Эта опция перезагружает данные о закрытых заголовках для воспроизводимого видео. Значение будет null
, если вы получите значение опции. Установите значениеtrue
, чтобы перезагрузить данные о закрытых заголовках.
-
onAutoplayBlocked
- Это событие стреляет в любое время, когда браузер блокирует автозаправленные или сценарии функций воспроизведения видео, которые в совокупности называют «AutoPlay». Это включает в себя воспроизведение, пытаясь с любым из следующих API игроков:
- параметр
autoplay
- функция
loadPlaylist
- функция
loadVideoById
- FUNCTION
loadVideoByUrl
- Функция
playVideo
Для получения полной информации обратитесь к политикам, специфичным для браузера ( Apple Safari / Webkit , Google Chrome , Mozilla Firefox ) и руководство Mozilla по автопластике . - параметр
Примеры
Создание объектов YT.Player
Пример 1: Используйте API с существующим <iframe>
В этом примере элемент
<iframe>
на странице уже определяет игрока, с которым будет использоваться API. Обратите внимание, что либо URLsrc
игрока должен установить параметрenablejsapi
на1
или атрибутenablejsapi
<iframe>
EnementJSAPI, который должен быть установлен наtrue
.Функция
onPlayerReady
меняет цвет границы вокруг игрока на апельсин, когда игрок готов. ФункцияonPlayerStateChange
затем меняет цвет границы вокруг игрока на основе текущего статуса игрока. Например, цвет зеленый, когда игрок играет, красный при приостановке, синий при буферизации и так далее.В этом примере используется следующий код:
<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: Громкое воспроизведение
Этот пример создает видеоплеер 1280px на 720px. Слушатель событий для события
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: Этот пример устанавливает параметры игрока для автоматического воспроизведения видео, когда оно загружается, и скрыть элементы управления видеоплеера. Это также добавляет слушателей событий для нескольких событий, которые транслирует API.
function onYouTubeIframeAPIReady() { var player; player = new YT.Player('player', { videoId: 'M7lc1UVf-VE', playerVars: { 'autoplay': 1, 'controls': 0 }, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange, 'onError': onPlayerError } }); }
Контроль 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 Integration API
YouTube расширил API API Android WebView Media Integrity , чтобы позволить встраиваемым медиа -игрокам, включая вставки игроков на YouTube в приложениях Android, чтобы проверить подлинность приложения Embedding. С этим изменением встраивание приложений автоматически отправляет затурсенный идентификатор приложения на YouTube. Данные, собранные с помощью использования этого API, представляют собой метаданные приложения (имя пакета, номер версии и сертификат подписания) и токен аттестации устройства, созданный Google Play Services.
Данные используются для проверки целостности приложения и устройства. Он зашифрован, не совместно используется с третьими лицами и удаляется после фиксированного периода хранения. Разработчики приложений могут настроить идентичность своего приложения в API 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 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
, andgetAvailableQualityLevels
functions are no longer supported. In particular, calls tosetPlaybackQuality
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 thesuggestedQuality
argument. Similarly, if you call those functions using object syntax, thesuggestedQuality
field is no longer supported. IfsuggestedQuality
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 toDeviceOrientationEvents
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 thecaptions
module and not thecc
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:
-
The new removeEventListener function lets you remove a listener for a specified event.
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 whenplayVideo()
is called. -
The
getVideoStartBytes
method has been deprecated. The method now always returns a value of0
.
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 theonYouTubeIframeAPIReady
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
onPlaybackRateChange
– This event fires when the video's playback rate changes.
-
July 19, 2012
This update contains the following changes:
-
The new
getVideoLoadedFraction
method replaces the now-deprecatedgetVideoBytesLoaded
andgetVideoBytesTotal
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 of5
, 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 namedonYouTubePlayerAPIReady
. 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 anonYouTubePlayerAPIReady
function, both functions will be called, and theonYouTubeIframeAPIReady
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()
anddestroy()
methods. ThesetSize()
method sets the size in pixels of the<iframe>
that contains the player and thedestroy()
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 aninline-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.
API Iframe Player позволяет вам встроить видеоплеер YouTube на вашем веб -сайте и управлять игроком с помощью JavaScript.
Используя функции JavaScript API, вы можете очереди видеоролики для воспроизведения; играть, сделать паузу или остановить эти видео; отрегулировать громкость игрока; или получить информацию о воспроизводимом видео. Вы также можете добавить слушателей событий, которые будут выполняться в ответ на определенные события игроков, такие как изменение состояния игрока.
Это руководство объясняет, как использовать API iframe. Он определяет различные типы событий, которые API может отправлять, и объясняет, как писать слушателей событий, чтобы ответить на эти события. В нем также подробно описываются различные функции JavaScript, которые вы можете позвонить, чтобы управлять видеоплером, а также параметры игрока, которые вы можете использовать для дальнейшей настройки игрока.
Требования
Браузер пользователя должен поддерживать функцию 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, также должна реализовать следующую функцию JavaScript:
onYouTubeIframeAPIReady
- API будет называть эту функцию, когда страница закончила загрузку JavaScript для API Player, который позволяет вам использовать 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>
В следующем списке приведен более подробная информация о примере выше:
Тег
<div>
в этом разделе идентифицирует местоположение на странице, где API IFRAME разместит видеоплеер. Конструктор для объекта Player, который описан в разделе «Загрузка видеоплеера» , определяет тег<div>
по егоid
, чтобы убедиться, что API помещает<iframe>
в соответствующем месте. В частности, API IFRAME заменит тег<div>
на тег<iframe>
.В качестве альтернативы вы также можете поместить элемент
<iframe>
прямо на страницу. В разделе «Загрузка видеопроглеза» объясняется, как это сделать.Код в этом разделе загружает API Iframe Player API JavaScript. В примере используется модификация DOM для загрузки кода API, чтобы убедиться, что код получен асинхронно. (
async
атрибут<script>
TAG, который также позволяет асинхронным загрузкам, еще не поддерживается во всех современных браузерах, как обсуждалось в этом ответе на переполнение стека .Функция
onYouTubeIframeAPIReady
будет выполняться, как только загружает код API игрока. Эта часть кода определяет глобальную переменную,player
, которая относится к видеоплееру, которого вы внедряете, и затем функция создает объект видеоплеера.Функция
onPlayerReady
будет выполняться, когда событиеonReady
запускается. В этом примере функция указывает, что когда видеоплеер готов, она должна начать играть.API будет называть функцию
onPlayerStateChange
, когда изменение состояния игрока, что может указывать на то, что игрок играет, приостанавливается, закончена и так далее. Функция указывает на то, что когда состояние игрока составляет1
(игра), игрок должен играть в течение шести секунд, а затем вызовать функциюstopVideo
, чтобы остановить видео.
Загрузка видеоплеера
После загрузки кода JavaScript 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 } }); }
Конструктор для видеоплеера определяет следующие параметры:
Первый параметр указывает либо элемент DOM, либо
id
элемента HTML, где API вставит тег<iframe>
, содержащий игрока.API IFRAME заменит указанный элемент на элемент
<iframe>
, содержащий игрока. Это может повлиять на макет вашей страницы, если заменяемый элемент имеет другой стиль отображения, чем вставленный элемент<iframe>
. По умолчанию<iframe>
отображается как элементinline-block
.- Второй параметр - это объект, который указывает параметры игрока. Объект содержит следующие свойства:
-
width
(номер) - ширина видеоплеере. Значение по умолчанию составляет640
. -
height
(номер) - высота видеоплеера. Значение по умолчанию составляет390
. -
videoId
(String) - идентификатор видео на YouTube, который идентифицирует видео, которое будет загружать игрок. -
playerVars
(объект) - свойства объекта идентифицируют параметры игрока , которые можно использовать для настройки игрока. -
events
(объект) - свойства объекта идентифицируют события, которые сжигает API, и функции (слушатели событий), которые API позволит, когда произойдут эти события. В примере конструктор указывает, что функцияonPlayerReady
будет выполняться при запуске событияonReady
и что функцияonPlayerStateChange
будет выполняться при запуске событияonStateChange
.
-
Как упомянуто в разделе « Начало работы <iframe>
, вместо того, чтобы записывать пустой элемент <div>
на вашей странице, который затем заменит код JavaScript Player API, вы можете создать теги <iframe>
. Первый пример в разделе «Примеры» показывает, как это сделать.
<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
не является обязательным, в том числе он защищает от злонамеренного стороннего JavaScript, введенного в вашу страницу и угнает контроль над вашим игроком на YouTube.
Для других примеров построения объектов видеоплеера см. Примеры .
Операции
Чтобы вызвать методы API Player, вы должны сначала получить ссылку на объект игрока, который вы хотите контролировать. Вы получаете ссылку, создав объект 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
Эта функция загружает миниатюру указанного видео и готовит игрока воспроизвести видео. Игрок не запрашивает FLV до тех пор, пока не будет вызван
playVideo()
илиseekTo()
.- Необходимый параметр
videoId
указывает идентификатор видео на YouTube видео, который будет воспроизводится. В API данных YouTube данныеid
video
ресурса указывают идентификатор. - Необязательный параметр
startSeconds
принимает плавание/целое число и указывает время, с которого видео должно начать воспроизводиться, когда называетсяplayVideo()
. Если вы указываете значениеstartSeconds
, а затем CALLseekTo()
, то игрок играет со времени, указанного в вызовеseekTo()
. Когда видео будет готово и готово к игре, игрок будет транслировать событиеvideo cued
(5
). - Необязательный параметр
endSeconds
, который поддерживается только в синтаксисе объектов, принимает поплавок/целое число и указывает время, когда видео должно прекратить воспроизведение, когда вызываетсяplayVideo()
. Если вы указываете значениеendSeconds
, а затем вызовутseekTo()
, значениеendSeconds
значения больше не будет действовать.
loadVideoById
Синтаксис аргументов
player.loadVideoById(videoId:String, startSeconds:Number):Void
Синтаксис объекта
player.loadVideoById({videoId:String, startSeconds:Number, endSeconds:Number}):Void
Эта функция загружает и воспроизводит указанное видео.
- Необходимый параметр
videoId
указывает идентификатор видео на YouTube видео, который будет воспроизводится. В API данных YouTube данныеid
video
ресурса указывают идентификатор. - Необязательный параметр
startSeconds
принимает плавание/целое число. Если это указано, то видео начнется с ближайшего ключа к указанному времени. - Необязательный параметр
endSeconds
принимает плавание/целое число. Если это указано, то видео перестанет играть в указанное время.
cueVideoByUrl
Синтаксис аргументов
player.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void
Синтаксис объекта
player.cueVideoByUrl({mediaContentUrl:String, startSeconds:Number, endSeconds:Number}):Void
Эта функция загружает миниатюру указанного видео и готовит игрока воспроизвести видео. Игрок не запрашивает FLV до тех пор, пока не будет вызван
playVideo()
илиseekTo()
.- Необходимый параметр
mediaContentUrl
указывает полностью квалифицированный URL -игрок YouTube в форматеhttp://www.youtube.com/v/VIDEO_ID?version=3
. - Необязательный параметр
startSeconds
принимает плавание/целое число и указывает время, с которого видео должно начать воспроизводиться, когда называетсяplayVideo()
. Если вы указываетеstartSeconds
, а затем вызовитеseekTo()
, то игрок играет со времени, указанного в вызовеseekTo()
. Когда видео будет готово и готово к игре, игрок будет транслировать событиеvideo cued
(5). - Необязательный параметр
endSeconds
, который поддерживается только в синтаксисе объектов, принимает поплавок/целое число и указывает время, когда видео должно прекратить воспроизведение, когда вызывается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
принимает плавание/целое число и указывает время, с которого видео должно начать воспроизводить. Если указаныstartSeconds
(номер может быть поплавок), видео начнется с ближайшего ключа к указанному времени. - Необязательный параметр
endSeconds
, который поддерживается только в синтаксисе объектов, принимает поплавок/целое число и указывает время, когда видео должно прекратить играть.
Функции очереди для списков
Функции cuePlaylist
и loadPlaylist
позволяют загружать и воспроизводить список воспроизведения. Если вы используете синтаксис объектов для вызова этих функций, вы также можете стоять в очереди (или загрузить) список загруженных видео пользователя.
Поскольку функции работают по -разному в зависимости от того, называются ли они с использованием синтаксиса аргумента или синтаксиса объекта, оба метода вызова задокументированы ниже.
-
cuePlaylist
Синтаксис аргументов
Очереди указанный список воспроизведения. Когда плейлист будет готов к игре, игрок будет транслировать событиеplayer.cuePlaylist(playlist:String|Array, index:Number, startSeconds:Number):Void
video cued
(5
).Требуемый параметр
playlist
определяет массив идентификаторов видео на YouTube. В API данных YouTube данныеid
video
ресурса определяют идентификатор этого видео.Необязательный параметр
index
указывает индекс первого видео в плейлисте, который будет воспроизводиться. Параметр использует индекс на основе нуля, а значение параметра по умолчанию составляет0
, поэтому поведение по умолчанию-загрузить и воспроизвести первое видео в списке воспроизведения.Необязательный параметр
startSeconds
принимает поплавок/целое число и определяет время, в которое первое видео в списке воспроизведения должно начинать воспроизведение, когда вызывается функцияplayVideo()
. Если вы указываете значениеstartSeconds
, а затем CALLseekTo()
, то игрок играет со времени, указанного в вызове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
указывает идентификатор Playlist или массив видео идентификаторов. В API данных YouTubeid
playlist
Resource идентифицируют идентификатор плейлиста, а свойствоid
video
ресурса определяет идентификатор видео. - Если значение свойства
listType
составляетuser_uploads
, то свойствоlist
идентифицирует пользователя, чьи загруженные видео будут возвращены. - Если значение свойства
listType
search
, то свойствоlist
указывает поисковый запрос. Примечание. Эта функциональность устарела и больше не будет поддерживаться по состоянию на15 ноября 2020 года .
- Если значение свойства
Необязательное свойство
index
указывает индекс первого видео в списке, который будет воспроизводиться. Параметр использует индекс на основе нуля, а значение параметра по умолчанию составляет0
, поэтому поведение по умолчанию-загрузить и воспроизвести первое видео в списке.Дополнительное свойство
startSeconds
принимает поплавок/целое число и определяет время, в которое первое видео в списке должно начать воспроизведение, когда вызывается функцияplayVideo()
. Если вы указываете значениеstartSeconds
, а затем CALLseekTo()
, то игрок играет со времени, указанного в вызовеseekTo()
. Если вы подскажите список, а затем вызовите функциюplayVideoAt()
, игрок начнет играть в начале указанного видео.
-
loadPlaylist
Синтаксис аргументов
Эта функция загружает указанный список воспроизведения и воспроизводит его.player.loadPlaylist(playlist:String|Array, index:Number, startSeconds:Number):Void
Требуемый параметр
playlist
определяет массив идентификаторов видео на YouTube. В API данных YouTube данныеid
video
ресурса определяют идентификатор видео.Необязательный параметр
index
указывает индекс первого видео в плейлисте, который будет воспроизводиться. Параметр использует индекс на основе нуля, а значение параметра по умолчанию составляет0
, поэтому поведение по умолчанию-загрузить и воспроизвести первое видео в списке воспроизведения.Необязательный параметр
startSeconds
принимает поплавок/целое число и указывает время, с которого должно начинать играть первое видео в списке воспроизведения.
Синтаксис объекта
Эта функция загружает указанный список и воспроизводит его. Список может быть списком воспроизведения или загруженного видеопользователя пользователя. Возможность загрузить список результатов поиска устарела и больше не будет поддерживаться по состоянию на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
определяет идентификатор плейлиста или массив видео идентификаторов. В API Data Data YouTube в свойствеid
ресурсаplaylist
определяется идентификатор плейлиста, а свойствоid
video
ресурса определяет идентификатор видео. - Если значение свойства
listType
составляетuser_uploads
, то свойствоlist
идентифицирует пользователя, чьи загруженные видео будут возвращены. - Если значение свойства
listType
search
, то свойствоlist
указывает поисковый запрос. Примечание. Эта функциональность устарела и больше не будет поддерживаться по состоянию на15 ноября 2020 года .
- Если значение свойства
Необязательное свойство
index
указывает индекс первого видео в списке, который будет воспроизводиться. Параметр использует индекс на основе нуля, а значение параметра по умолчанию составляет0
, поэтому поведение по умолчанию-загрузить и воспроизвести первое видео в списке.Дополнительное свойство
startSeconds
принимает поплавок/целое число и определяет время, с которого первое видео в списке должно начать играть.
Управление воспроизведения и настройки игрока
Воспроизведение видео
-
player. playVideo ():Void
- Играет в настоящее время видео в настоящее время. Окончательное состояние игрока после выполнения этой функции будет
playing
(1).
Примечание. Воспроизведение имеет значение для официального количества представлений видео, только если оно инициируется через нативную кнопку воспроизведения в игроке.
-
player. pauseVideo ():Void
- Сделает паузу в настоящее время воспроизводимое видео. Окончательное состояние игрока после выполнения этой функции будет
paused
(2
), если игрок не будет вended
(0
) состоянии при вызове функции, и в этом случае состояние игрока не изменится.
-
player. stopVideo ():Void
- Останавливает и отменяет загрузку текущего видео. Эта функция должна быть зарезервирована для редких ситуаций, когда вы знаете, что пользователь не будет смотреть дополнительное видео в игроке. Если ваше намерение состоит в том, чтобы приостановить видео, вам следует просто вызвать функцию
pauseVideo
. Если вы хотите изменить видео, в котором играет игрок, вы можете позвонить в одну из функций очереди, не вызывая сначалаstopVideo
.
ВАЖНО: В отличие от функцииpauseVideo
, которая оставляет игрока в состоянииpaused
(2
), функцияstopVideo
может поместить игрока в любое неживое состояние, включаяended
(0
),paused
(2
),video 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), которое представляет горизонтальный угол вида в градусах, что отражает степень, в которой пользователь поворачивает представление, чтобы обратиться к дальнейшему слева или вправо. Нейтральная позиция, обращенная к центру видео в его экваsirectangular проекции, представляет 0 °, и это значение увеличивается, когда зритель поворачивается влево. pitch
Число в диапазоне [-90, 90], которое представляет вертикальный угол вида в градусах, что отражает степень, в которой пользователь регулирует вид, чтобы посмотреть или вниз. Нейтральная позиция, обращенная к центру видео в его экваsirectangular проекции, представляет 0 °, и это значение увеличивается, когда зритель смотрит вверх. roll
Число в диапазоне [-180, 180], которое представляет собой угол вращения по часовой стрелке или против часовой стрелки в градусах. Нейтральное положение, с горизонтальной осью в эквалентной проекции, параллельной горизонтальной оси вида, представляет 0 °. Значение увеличивается, когда вид вращается по часовой стрелке и уменьшается, когда вид вращается против часовой стрелки.
Обратите внимание, что встроенный игрок не представляет пользовательский интерфейс для настройки броска вида. Ролл можно скорректировать любым из этих взаимоисключающих способов:- Используйте датчик ориентации в мобильном браузере, чтобы обеспечить бросок для вида. Если датчик ориентации включен, то функция
getSphericalProperties
всегда возвращает0
в качестве значения свойстваroll
. - Если датчик ориентации отключен, установите рулон на ненулевое значение, используя этот API.
fov
Число в диапазоне [30, 120], которое представляет поле зрения в градусах, измеряемых вдоль более длинного края просмотра. Более короткий край автоматически корректируется, чтобы быть пропорциональным соотношению сторон.
Значение по умолчанию составляет 100 градусов. Уменьшение значения похоже на увеличение видеоконтента, а увеличение значения похоже на увеличение. Это значение можно скорректировать либо с помощью API, либо с помощью мышиного колеса, когда видео находится в полноэкранном режиме.
-
player. setSphericalProperties (properties:Object):Void
- Устанавливает ориентацию видео для воспроизведения видео 360 °. (Если текущее видео не является сферическим, метод не является OP, независимо от ввода.)
Представление игрока отвечает на вызовы на этот метод, обновляя, чтобы отразить значения любых известных свойств в объектеproperties
. Взгляд сохраняет значения для любых других известных свойств, не включенных в этот объект.
Кроме того:- Если объект содержит неизвестные и/или неожиданные свойства, игрок игнорирует их.
- Как отмечалось в начале этого раздела, опыт воспроизведения видео на 360 ° не поддерживается на всех мобильных устройствах.
- По умолчанию, на поддерживаемых мобильных устройствах эта набор функций устанавливает свойство
fov
и не влияет на свойстваyaw
,pitch
иroll
для воспроизведения видео на 360 °. See theenableOrientationSensor
property below for more detail.
properties
object passed to the function contains the following properties:Характеристики yaw
See definition above. pitch
See definition above. roll
See definition above. fov
See definition above. enableOrientationSensor
Note: This property affects the 360° viewing experience on supported devices only. A boolean value that indicates whether the IFrame embed should respond to events that signal changes in a supported device's orientation, such as a mobile browser's DeviceOrientationEvent
. The default parameter value istrue
.
Supported mobile devices- When the value is
true
, an embedded player relies only on the device's movement to adjust theyaw
,pitch
, androll
properties for 360° video playbacks. However, thefov
property can still be changed via the API, and the API is, in fact, the only way to change thefov
property on a mobile device. This is the default behavior. - When the value is
false
, then the device's movement does not affect the 360° viewing experience, and theyaw
,pitch
,roll
, andfov
properties must all be set via the API.
Unsupported mobile devices
TheenableOrientationSensor
property value does not have any effect on the playback experience.
Playing a video in a playlist
-
player. nextVideo ():Void
- This function loads and plays the next video in the playlist.
If
player.nextVideo()
is called while the last video in the playlist is being watched, and the playlist is set to play continuously (loop
), then the player will load and play the first video in the list.If
player.nextVideo()
is called while the last video in the playlist is being watched, and the playlist is not set to play continuously, then playback will end.
-
player. previousVideo ():Void
- This function loads and plays the previous video in the playlist.
If
player.previousVideo()
is called while the first video in the playlist is being watched, and the playlist is set to play continuously (loop
), then the player will load and play the last video in the list.If
player.previousVideo()
is called while the first video in the playlist is being watched, and the playlist is not set to play continuously, then the player will restart the first playlist video from the beginning.
-
player. playVideoAt (index:Number):Void
- This function loads and plays the specified video in the playlist.
The required
index
parameter specifies the index of the video that you want to play in the playlist. The parameter uses a zero-based index, so a value of0
identifies the first video in the list. If you have shuffled the playlist, this function will play the video at the specified position in the shuffled playlist.
Changing the player volume
-
player. mute ():Void
- Mutes the player.
-
player. unMute ():Void
- Unmutes the player.
-
player. isMuted ():Boolean
- Returns
true
if the player is muted,false
if not.
-
player. setVolume (volume:Number):Void
- Sets the volume. Accepts an integer between
0
and100
.
-
player. getVolume ():Number
- Returns the player's current volume, an integer between
0
and100
. Note thatgetVolume()
will return the volume even if the player is muted.
Setting the player size
-
player.setSize(width:Number, height:Number):Object
- Sets the size in pixels of the
<iframe>
that contains the player.
Setting the playback rate
-
player. getPlaybackRate ():Number
- This function retrieves the playback rate of the currently playing video. The default playback rate is
1
, which indicates that the video is playing at normal speed. Playback rates may include values like0.25
,0.5
,1
,1.5
, and2
.
-
player. setPlaybackRate (suggestedRate:Number):Void
- This function sets the suggested playback rate for the current video. If the playback rate changes, it will only change for the video that is already cued or being played. If you set the playback rate for a cued video, that rate will still be in effect when the
playVideo
function is called or the user initiates playback directly through the player controls. In addition, calling functions to cue or load videos or playlists (cueVideoById
,loadVideoById
, etc.) will reset the playback rate to1
.
Calling this function does not guarantee that the playback rate will actually change. However, if the playback rate does change, theonPlaybackRateChange
event will fire, and your code should respond to the event rather than the fact that it called thesetPlaybackRate
function.
ThegetAvailablePlaybackRates
method will return the possible playback rates for the currently playing video. However, if you set thesuggestedRate
parameter to a non-supported integer or float value, the player will round that value down to the nearest supported value in the direction of1
.
-
player. getAvailablePlaybackRates ():Array
- This function returns the set of playback rates in which the current video is available. The default value is
1
, which indicates that the video is playing in normal speed.
The function returns an array of numbers ordered from slowest to fastest playback speed. Even if the player does not support variable playback speeds, the array should always contain at least one value (1
).
Setting playback behavior for playlists
-
player. setLoop (loopPlaylists:Boolean):Void
This function indicates whether the video player should continuously play a playlist or if it should stop playing after the last video in the playlist ends. The default behavior is that playlists do not loop.
This setting will persist even if you load or cue a different playlist, which means that if you load a playlist, call the
setLoop
function with a value oftrue
, and then load a second playlist, the second playlist will also loop.The required
loopPlaylists
parameter identifies the looping behavior.If the parameter value is
true
, then the video player will continuously play playlists. After playing the last video in a playlist, the video player will go back to the beginning of the playlist and play it again.If the parameter value is
false
, then playbacks will end after the video player plays the last video in a playlist.
-
player. setShuffle (shufflePlaylist:Boolean):Void
This function indicates whether a playlist's videos should be shuffled so that they play back in an order different from the one that the playlist creator designated. If you shuffle a playlist after it has already started playing, the list will be reordered while the video that is playing continues to play. The next video that plays will then be selected based on the reordered list.
This setting will not persist if you load or cue a different playlist, which means that if you load a playlist, call the
setShuffle
function, and then load a second playlist, the second playlist will not be shuffled.The required
shufflePlaylist
parameter indicates whether YouTube should shuffle the playlist.If the parameter value is
true
, then YouTube will shuffle the playlist order. If you instruct the function to shuffle a playlist that has already been shuffled, YouTube will shuffle the order again.If the parameter value is
false
, then YouTube will change the playlist order back to its original order.
Playback status
-
player. getVideoLoadedFraction ():Float
- Returns a number between
0
and1
that specifies the percentage of the video that the player shows as buffered. This method returns a more reliable number than the now-deprecatedgetVideoBytesLoaded
andgetVideoBytesTotal
methods.
-
player.getPlayerState():Number
- Returns the state of the player. Возможные значения:
-
-1
– unstarted -
0
– ended -
1
– playing -
2
– paused -
3
– buffering -
5
– video cued
-
-
player. getCurrentTime ():Number
- Returns the elapsed time in seconds since the video started playing.
-
player. getVideoStartBytes ():Number
- Deprecated as of October 31, 2012. Returns the number of bytes the video file started loading from. (This method now always returns a value of
0
.) Example scenario: the user seeks ahead to a point that hasn't loaded yet, and the player makes a new request to play a segment of the video that hasn't loaded yet.
-
player. getVideoBytesLoaded ():Number
- Deprecated as of July 18, 2012. Instead, use the
getVideoLoadedFraction
method to determine the percentage of the video that has buffered.
This method returns a value between0
and1000
that approximates the amount of the video that has been loaded. You could calculate the fraction of the video that has been loaded by dividing thegetVideoBytesLoaded
value by thegetVideoBytesTotal
value.
-
player. getVideoBytesTotal ():Number
- Deprecated as of July 18, 2012. Instead, use the
getVideoLoadedFraction
method to determine the percentage of the video that has buffered.
Returns the size in bytes of the currently loaded/playing video or an approximation of the video's size.
This method always returns a value of1000
. You could calculate the fraction of the video that has been loaded by dividing thegetVideoBytesLoaded
value by thegetVideoBytesTotal
value.
Retrieving video information
-
player. getDuration ():Number
- Returns the duration in seconds of the currently playing video. Note that
getDuration()
will return0
until the video's metadata is loaded, which normally happens just after the video starts playing.
If the currently playing video is a live event , thegetDuration()
function will return the elapsed time since the live video stream began. Specifically, this is the amount of time that the video has streamed without being reset or interrupted. In addition, this duration is commonly longer than the actual event time since streaming may begin before the event's start time.
-
player. getVideoUrl ():String
- Returns the YouTube.com URL for the currently loaded/playing video.
-
player. getVideoEmbedCode ():String
- Returns the embed code for the currently loaded/playing video.
Retrieving playlist information
-
player. getPlaylist ():Array
- This function returns an array of the video IDs in the playlist as they are currently ordered. 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 thegetPlaylist()
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
. Thelistener
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.
События
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 theonReady
andonAutoplayBlocked
events do not specify adata
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 atarget
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 anid
value ofembed-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. Возможные значения:-
-1
(unstarted) -
0
(ended) -
1
(playing) -
2
(paused) -
3
(buffering) -
5
(video cued).
unstarted
(-1
) event. When a video is cued and ready to play, the player will broadcast avideo 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.
Thedata
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. Возможные значения:-
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 thesetPlaybackRate(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 tosetPlaybackRate
.
Thedata
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. ThegetAvailablePlaybackRates
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'sdata
property will specify an integer that identifies the type of error that occurred. Возможные значения:-
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 as101
. It's just a101
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: Currently, the only module that you can set options for is theplayer.getOptions();
captions
module, which handles closed captioning in the player. Upon receiving anonApiChange
event, your application can use the following command to determine which options can be set for thecaptions
module: 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:player.getOptions('captions');
The table below lists the options that the API supports:Retrieving an option: player.getOption(module, option); Setting an option player.setOption(module, option, value);
Модуль Вариант Описание captions fontSize This option adjusts the font size of the captions displayed in the player.
Valid values are-1
,0
,1
,2
, and3
. The default size is0
, 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 above3
will cause the largest caption size to display.captions reload 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 totrue
to reload the closed caption data.
-
onAutoplayBlocked
- This event fires any time the browser blocks autoplay or scripted video playback features, collectively referred to as "autoplay". This includes playback attempted with any of the following player APIs:
-
autoplay
parameter -
loadPlaylist
function -
loadVideoById
function -
loadVideoByUrl
function -
playVideo
function
For complete details, refer to browser-specific policies ( Apple Safari / Webkit , Google Chrome , Mozilla Firefox ) and Mozilla's autoplay guide . -
Примеры
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'ssrc
URL must set theenablejsapi
parameter to1
or the<iframe>
element'senablejsapi
attribute must be set totrue
.The
onPlayerReady
function changes the color of the border around the player to orange when the player is ready. TheonPlayerStateChange
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 thesetVolume
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>
Android WebView Media Integrity API integration
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. The data collected through usage of this API is the app metadata (the package name, version number, and signing certificate) and a device attestation token generated by Google Play services.
The data is used to verify the application and device integrity. It is encrypted, not shared with third parties, and deleted following a fixed retention period. App developers can configure their app identity in the WebView Media Integrity API. The configuration supports an opt-out option.
История изменений
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 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
, andgetAvailableQualityLevels
functions are no longer supported. In particular, calls tosetPlaybackQuality
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 thesuggestedQuality
argument. Similarly, if you call those functions using object syntax, thesuggestedQuality
field is no longer supported. IfsuggestedQuality
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 toDeviceOrientationEvents
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 thecaptions
module and not thecc
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:
-
The new removeEventListener function lets you remove a listener for a specified event.
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 whenplayVideo()
is called. -
The
getVideoStartBytes
method has been deprecated. The method now always returns a value of0
.
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 theonYouTubeIframeAPIReady
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
onPlaybackRateChange
– This event fires when the video's playback rate changes.
-
July 19, 2012
This update contains the following changes:
-
The new
getVideoLoadedFraction
method replaces the now-deprecatedgetVideoBytesLoaded
andgetVideoBytesTotal
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 of5
, 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 namedonYouTubePlayerAPIReady
. 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 anonYouTubePlayerAPIReady
function, both functions will be called, and theonYouTubeIframeAPIReady
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()
anddestroy()
methods. ThesetSize()
method sets the size in pixels of the<iframe>
that contains the player and thedestroy()
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 aninline-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.
The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript.
Using the API's JavaScript functions, you can queue videos for playback; play, pause, or stop those videos; adjust the player volume; or retrieve information about the video being played. You can also add event listeners that will execute in response to certain player events, such as a player state change.
This guide explains how to use the IFrame API. It identifies the different types of events that the API can send and explains how to write event listeners to respond to those events. It also details the different JavaScript functions that you can call to control the video player as well as the player parameters you can use to further customize the player.
Требования
The user's browser must support the HTML5 postMessage
feature. Most modern browsers support 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.
Any web page that uses the IFrame API must also implement the following JavaScript function:
onYouTubeIframeAPIReady
– The API will call this function when the page has finished downloading the JavaScript for the player API, which enables you to then use the API on your page. Thus, this function might create the player objects that you want to display when the page loads.
Начиная
The sample HTML page below creates an embedded player that will load a video, play it for six seconds, and then stop the playback. The numbered comments in the HTML are explained in the list below the example.
<!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>
The following list provides more details about the sample above:
The
<div>
tag in this section identifies the location on the page where the IFrame API will place the video player. The constructor for the player object, which is described in the Loading a video player section, identifies the<div>
tag by itsid
to ensure that the API places the<iframe>
in the proper location. Specifically, the IFrame API will replace the<div>
tag with the<iframe>
tag.As an alternative, you could also put the
<iframe>
element directly on the page. The Loading a video player section explains how to do so.The code in this section loads the IFrame Player API JavaScript code. The example uses DOM modification to download the API code to ensure that the code is retrieved asynchronously. (The
<script>
tag'sasync
attribute, which also enables asynchronous downloads, is not yet supported in all modern browsers as discussed in this Stack Overflow answer .The
onYouTubeIframeAPIReady
function will execute as soon as the player API code downloads. This portion of the code defines a global variable,player
, which refers to the video player you are embedding, and the function then constructs the video player object.The
onPlayerReady
function will execute when theonReady
event fires. In this example, the function indicates that when the video player is ready, it should begin to play.The API will call the
onPlayerStateChange
function when the player's state changes, which may indicate that the player is playing, paused, finished, and so forth. The function indicates that when the player state is1
(playing), the player should play for six seconds and then call thestopVideo
function to stop the video.
Loading a video player
After the API's JavaScript code loads, the API will call the onYouTubeIframeAPIReady
function, at which point you can construct a YT.Player
object to insert a video player on your page. The HTML excerpt below shows the onYouTubeIframeAPIReady
function from the example above:
var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '390', width: '640', videoId: 'M7lc1UVf-VE', playerVars: { 'playsinline': 1 }, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); }
The constructor for the video player specifies the following parameters:
The first parameter specifies either the DOM element or the
id
of the HTML element where the API will insert the<iframe>
tag containing the player.The IFrame API will replace the specified element with the
<iframe>
element containing the player. This 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 aninline-block
element.- The second parameter is an object that specifies player options. The object contains the following properties:
-
width
(number) – The width of the video player. The default value is640
. -
height
(number) – The height of the video player. The default value is390
. -
videoId
(string) – The YouTube video ID that identifies the video that the player will load. -
playerVars
(object) – The object's properties identify player parameters that can be used to customize the player. -
events
(object) – The object's properties identify the events that the API fires and the functions (event listeners) that the API will call when those events occur. In the example, the constructor indicates that theonPlayerReady
function will execute when theonReady
event fires and that theonPlayerStateChange
function will execute when theonStateChange
event fires.
-
As mentioned in the Getting started section, instead of writing an empty <div>
element on your page, which the player API's JavaScript code will then replace with an <iframe>
element, you could create the <iframe>
tag yourself. The first example in the Examples section shows how to do this.
<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>
Note that if you do write the <iframe>
tag, then when you construct the YT.Player
object, you do not need to specify values for the width
and height
, which are specified as attributes of the <iframe>
tag, or the videoId
and player parameters, which are are specified in the src
URL. As an extra security measure, you should also include the origin
parameter to the URL, specifying the URL scheme ( http://
or https://
) and full domain of your host page as the parameter value. While origin
is optional, including it protects against malicious third-party JavaScript being injected into your page and hijacking control of your YouTube player.
For other examples on constructing video player objects, see Examples .
Операции
To call the player API methods, you must first get a reference to the player object you wish to control. You obtain the reference by creating a YT.Player
object as discussed in the Getting started and Loading a video player sections of this document.
Функции
Queueing functions
Queueing functions allow you to load and play a video, a playlist, or another list of videos. If you are using the object syntax described below to call these functions, then you can also queue or load a list of a user's uploaded videos.
The API supports two different syntaxes for calling the queueing functions.
The argument syntax requires function arguments to be listed in a prescribed order.
The object syntax lets you pass an object as a single parameter and to define object properties for the function arguments that you wish to set. In addition, the API may support additional functionality that the argument syntax does not support.
For example, the loadVideoById
function can be called in either of the following ways. Note that the object syntax supports the endSeconds
property, which the argument syntax does not support.
Argument syntax
loadVideoById("bHQqvYy5KYo", 5, "large")
Object syntax
loadVideoById({'videoId': 'bHQqvYy5KYo', 'startSeconds': 5, 'endSeconds': 60});
Queueing functions for videos
-
cueVideoById
Argument syntax
player.cueVideoById(videoId:String, startSeconds:Number):Void
Object syntax
player.cueVideoById({videoId:String, startSeconds:Number, endSeconds:Number}):Void
This function loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until
playVideo()
orseekTo()
is called.- The required
videoId
parameter specifies the YouTube Video ID of the video to be played. In the YouTube Data API, avideo
resource'sid
property specifies the ID. - The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the video should start playing whenplayVideo()
is called. If you specify astartSeconds
value and then callseekTo()
, then the player plays from the time specified in theseekTo()
call. When the video is cued and ready to play, the player will broadcast avideo cued
event (5
). - The optional
endSeconds
parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop playing whenplayVideo()
is called. If you specify anendSeconds
value and then callseekTo()
, theendSeconds
value will no longer be in effect.
loadVideoById
Argument syntax
player.loadVideoById(videoId:String, startSeconds:Number):Void
Object syntax
player.loadVideoById({videoId:String, startSeconds:Number, endSeconds:Number}):Void
This function loads and plays the specified video.
- The required
videoId
parameter specifies the YouTube Video ID of the video to be played. In the YouTube Data API, avideo
resource'sid
property specifies the ID. - The optional
startSeconds
parameter accepts a float/integer. If it is specified, then the video will start from the closest keyframe to the specified time. - The optional
endSeconds
parameter accepts a float/integer. If it is specified, then the video will stop playing at the specified time.
cueVideoByUrl
Argument syntax
player.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void
Object syntax
player.cueVideoByUrl({mediaContentUrl:String, startSeconds:Number, endSeconds:Number}):Void
This function loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until
playVideo()
orseekTo()
is called.- The required
mediaContentUrl
parameter specifies a fully qualified YouTube player URL in the formathttp://www.youtube.com/v/VIDEO_ID?version=3
. - The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the video should start playing whenplayVideo()
is called. If you specifystartSeconds
and then callseekTo()
, then the player plays from the time specified in theseekTo()
call. When the video is cued and ready to play, the player will broadcast avideo cued
event (5). - The optional
endSeconds
parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop playing whenplayVideo()
is called. If you specify anendSeconds
value and then callseekTo()
, theendSeconds
value will no longer be in effect.
loadVideoByUrl
Argument syntax
player.loadVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void
Object syntax
player.loadVideoByUrl({mediaContentUrl:String, startSeconds:Number, endSeconds:Number}):Void
This function loads and plays the specified video.
- The required
mediaContentUrl
parameter specifies a fully qualified YouTube player URL in the formathttp://www.youtube.com/v/VIDEO_ID?version=3
. - The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the video should start playing. IfstartSeconds
(number can be a float) is specified, the video will start from the closest keyframe to the specified time. - The optional
endSeconds
parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop playing.
Queueing functions for lists
The cuePlaylist
and loadPlaylist
functions allow you to load and play a playlist. If you are using object syntax to call these functions, you can also queue (or load) a list of a user's uploaded videos.
Since the functions work differently depending on whether they are called using the argument syntax or the object syntax, both calling methods are documented below.
-
cuePlaylist
Argument syntax
Queues the specified playlist. When the playlist is cued and ready to play, the player will broadcast aplayer.cuePlaylist(playlist:String|Array, index:Number, startSeconds:Number):Void
video cued
event (5
).The required
playlist
parameter specifies an array of YouTube video IDs. In the YouTube Data API, thevideo
resource'sid
property identifies that video's ID.The optional
index
parameter specifies the index of the first video in the playlist that will play. The parameter uses a zero-based index, and the default parameter value is0
, so the default behavior is to load and play the first video in the playlist.The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the first video in the playlist should start playing when theplayVideo()
function is called. If you specify astartSeconds
value and then callseekTo()
, then the player plays from the time specified in theseekTo()
call. If you cue a playlist and then call theplayVideoAt()
function, the player will start playing at the beginning of the specified video.
Object syntax
Queues the specified list of videos. The list can be a playlist or a user's uploaded videos feed. The ability to queue a list of search results is deprecated and will no longer be supported as ofplayer.cuePlaylist({listType:String, list:String, index:Number, startSeconds:Number}):Void
15 November 2020 .When the list is cued and ready to play, the player will broadcast a
video cued
event (5
).The optional
listType
property specifies the type of results feed that you are retrieving. Valid values areplaylist
anduser_uploads
. A deprecated value,search
, will no longer be supported as of15 November 2020 . The default value isplaylist
.The required
list
property contains a key that identifies the particular list of videos that YouTube should return.- If the
listType
property value isplaylist
, then thelist
property specifies the playlist ID or an array of video IDs. In the YouTube Data API, theplaylist
resource'sid
property identifies a playlist's ID, and thevideo
resource'sid
property specifies a video ID. - If the
listType
property value isuser_uploads
, then thelist
property identifies the user whose uploaded videos will be returned. - If the
listType
property value issearch
, then thelist
property specifies the search query. Note: This functionality is deprecated and will no longer be supported as of15 November 2020 .
- If the
The optional
index
property specifies the index of the first video in the list that will play. The parameter uses a zero-based index, and the default parameter value is0
, so the default behavior is to load and play the first video in the list.The optional
startSeconds
property accepts a float/integer and specifies the time from which the first video in the list should start playing when theplayVideo()
function is called. If you specify astartSeconds
value and then callseekTo()
, then the player plays from the time specified in theseekTo()
call. If you cue a list and then call theplayVideoAt()
function, the player will start playing at the beginning of the specified video.
-
loadPlaylist
Argument syntax
This function loads the specified playlist and plays it.player.loadPlaylist(playlist:String|Array, index:Number, startSeconds:Number):Void
The required
playlist
parameter specifies an array of YouTube video IDs. In the YouTube Data API, thevideo
resource'sid
property specifies a video ID.The optional
index
parameter specifies the index of the first video in the playlist that will play. The parameter uses a zero-based index, and the default parameter value is0
, so the default behavior is to load and play the first video in the playlist.The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the first video in the playlist should start playing.
Object syntax
This function loads the specified list and plays it. The list can be a playlist or a user's uploaded videos feed. The ability to load a list of search results is deprecated and will no longer be supported as ofplayer.loadPlaylist({list:String, listType:String, index:Number, startSeconds:Number}):Void
15 November 2020 .The optional
listType
property specifies the type of results feed that you are retrieving. Valid values areplaylist
anduser_uploads
. A deprecated value,search
, will no longer be supported as of15 November 2020 . The default value isplaylist
.The required
list
property contains a key that identifies the particular list of videos that YouTube should return.- If the
listType
property value isplaylist
, then thelist
property specifies a playlist ID or an array of video IDs. In the YouTube Data API, theplaylist
resource'sid
property specifies a playlist's ID, and thevideo
resource'sid
property specifies a video ID. - If the
listType
property value isuser_uploads
, then thelist
property identifies the user whose uploaded videos will be returned. - If the
listType
property value issearch
, then thelist
property specifies the search query. Note: This functionality is deprecated and will no longer be supported as of15 November 2020 .
- If the
The optional
index
property specifies the index of the first video in the list that will play. The parameter uses a zero-based index, and the default parameter value is0
, so the default behavior is to load and play the first video in the list.The optional
startSeconds
property accepts a float/integer and specifies the time from which the first video in the list should start playing.
Playback controls and player settings
Воспроизведение видео
-
player. playVideo ():Void
- Plays the currently cued/loaded video. The final player state after this function executes will be
playing
(1).
Note: A playback only counts toward a video's official view count if it is initiated via a native play button in the player.
-
player. pauseVideo ():Void
- Pauses the currently playing video. The final player state after this function executes will be
paused
(2
) unless the player is in theended
(0
) state when the function is called, in which case the player state will not change.
-
player. stopVideo ():Void
- Stops and cancels loading of the current video. This function should be reserved for rare situations when you know that the user will not be watching additional video in the player. If your intent is to pause the video, you should just call the
pauseVideo
function. If you want to change the video that the player is playing, you can call one of the queueing functions without callingstopVideo
first.
Important: Unlike thepauseVideo
function, which leaves the player in thepaused
(2
) state, thestopVideo
function could put the player into any not-playing state, includingended
(0
),paused
(2
),video cued
(5
) orunstarted
(-1
).
-
player. seekTo (seconds:Number, allowSeekAhead:Boolean):Void
- Seeks to a specified time in the video. If the player is paused when the function is called, it will remain paused. If the function is called from another state (
playing
,video cued
, etc.), the player will play the video.The
seconds
parameter identifies the time to which the player should advance.The player will advance to the closest keyframe before that time unless the player has already downloaded the portion of the video to which the user is seeking.
The
allowSeekAhead
parameter determines whether the player will make a new request to the server if theseconds
parameter specifies a time outside of the currently buffered video data.We recommend that you set this parameter to
false
while the user drags the mouse along a video progress bar and then set it totrue
when the user releases the mouse. This approach lets a user scroll to different points of a video without requesting new video streams by scrolling past unbuffered points in the video. When the user releases the mouse button, the player advances to the desired point in the video and requests a new video stream if necessary.
Controlling playback of 360° videos
Note: The 360° video playback experience has limited support on mobile devices. On unsupported devices, 360° videos appear distorted and there is no supported way to change the viewing perspective at all, including through the API, using orientation sensors, or responding to touch/drag actions on the device's screen.
-
player. getSphericalProperties ():Object
- Retrieves properties that describe the viewer's current perspective, or view, for a video playback. Кроме того:
- This object is only populated for 360° videos, which are also called spherical videos.
- If the current video is not a 360° video or if the function is called from a non-supported device, then the function returns an empty object.
- On supported mobile devices, if the
enableOrientationSensor
property is set totrue
, then this function returns an object in which thefov
property contains the correct value and the other properties are set to0
.
Характеристики yaw
A number in the range [0, 360) that 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. The neutral position, facing the center of the video in its equirectangular projection, represents 0°, and this value increases as the viewer turns left. pitch
A number in the range [-90, 90] that 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. The neutral position, facing the center of the video in its equirectangular projection, represents 0°, and this value increases as the viewer looks up. roll
A number in the range [-180, 180] that represents the clockwise or counterclockwise rotational angle of the view in degrees. The neutral position, with the horizontal axis in the equirectangular projection being parallel to the horizontal axis of the view, represents 0°. The value increases as the view rotates clockwise and decreases as the view rotates counterclockwise.
Note that the embedded player does not present a user interface for adjusting the roll of the view. The roll can be adjusted in either of these mutually exclusive ways:- Use the orientation sensor in a mobile browser to provide roll for the view. If the orientation sensor is enabled, then the
getSphericalProperties
function always returns0
as the value of theroll
property. - If the orientation sensor is disabled, set the roll to a nonzero value using this API.
fov
A number in the range [30, 120] that represents the field-of-view of the view in degrees as measured along the longer edge of the viewport. The shorter edge is automatically adjusted to be proportional to the aspect ratio of the view.
The default value is 100 degrees. Decreasing the value is like zooming in on the video content, and increasing the value is like zooming out. This value can be adjusted either by using the API or by using the mousewheel when the video is in fullscreen mode.
-
player. setSphericalProperties (properties:Object):Void
- Sets the video orientation for playback of a 360° video. (If the current video is not spherical, the method is a no-op regardless of the input.)
The player view responds to calls to this method by updating to reflect the values of any known properties in theproperties
object. The view persists values for any other known properties not included in that object.
Кроме того:- If the object contains unknown and/or unexpected properties, the player ignores them.
- As noted at the beginning of this section, the 360° video playback experience is not supported on all mobile devices.
- By default, on supported mobile devices, this function sets only sets the
fov
property and does not affect theyaw
,pitch
, androll
properties for 360° video playbacks. See theenableOrientationSensor
property below for more detail.
properties
object passed to the function contains the following properties:Характеристики yaw
See definition above. pitch
See definition above. roll
See definition above. fov
See definition above. enableOrientationSensor
Note: This property affects the 360° viewing experience on supported devices only. A boolean value that indicates whether the IFrame embed should respond to events that signal changes in a supported device's orientation, such as a mobile browser's DeviceOrientationEvent
. The default parameter value istrue
.
Supported mobile devices- When the value is
true
, an embedded player relies only on the device's movement to adjust theyaw
,pitch
, androll
properties for 360° video playbacks. However, thefov
property can still be changed via the API, and the API is, in fact, the only way to change thefov
property on a mobile device. This is the default behavior. - When the value is
false
, then the device's movement does not affect the 360° viewing experience, and theyaw
,pitch
,roll
, andfov
properties must all be set via the API.
Unsupported mobile devices
TheenableOrientationSensor
property value does not have any effect on the playback experience.
Playing a video in a playlist
-
player. nextVideo ():Void
- This function loads and plays the next video in the playlist.
If
player.nextVideo()
is called while the last video in the playlist is being watched, and the playlist is set to play continuously (loop
), then the player will load and play the first video in the list.If
player.nextVideo()
is called while the last video in the playlist is being watched, and the playlist is not set to play continuously, then playback will end.
-
player. previousVideo ():Void
- This function loads and plays the previous video in the playlist.
If
player.previousVideo()
is called while the first video in the playlist is being watched, and the playlist is set to play continuously (loop
), then the player will load and play the last video in the list.If
player.previousVideo()
is called while the first video in the playlist is being watched, and the playlist is not set to play continuously, then the player will restart the first playlist video from the beginning.
-
player. playVideoAt (index:Number):Void
- This function loads and plays the specified video in the playlist.
The required
index
parameter specifies the index of the video that you want to play in the playlist. The parameter uses a zero-based index, so a value of0
identifies the first video in the list. If you have shuffled the playlist, this function will play the video at the specified position in the shuffled playlist.
Changing the player volume
-
player. mute ():Void
- Mutes the player.
-
player. unMute ():Void
- Unmutes the player.
-
player. isMuted ():Boolean
- Returns
true
if the player is muted,false
if not.
-
player. setVolume (volume:Number):Void
- Sets the volume. Accepts an integer between
0
and100
.
-
player. getVolume ():Number
- Returns the player's current volume, an integer between
0
and100
. Note thatgetVolume()
will return the volume even if the player is muted.
Setting the player size
-
player.setSize(width:Number, height:Number):Object
- Sets the size in pixels of the
<iframe>
that contains the player.
Setting the playback rate
-
player. getPlaybackRate ():Number
- This function retrieves the playback rate of the currently playing video. The default playback rate is
1
, which indicates that the video is playing at normal speed. Playback rates may include values like0.25
,0.5
,1
,1.5
, and2
.
-
player. setPlaybackRate (suggestedRate:Number):Void
- This function sets the suggested playback rate for the current video. If the playback rate changes, it will only change for the video that is already cued or being played. If you set the playback rate for a cued video, that rate will still be in effect when the
playVideo
function is called or the user initiates playback directly through the player controls. In addition, calling functions to cue or load videos or playlists (cueVideoById
,loadVideoById
, etc.) will reset the playback rate to1
.
Calling this function does not guarantee that the playback rate will actually change. However, if the playback rate does change, theonPlaybackRateChange
event will fire, and your code should respond to the event rather than the fact that it called thesetPlaybackRate
function.
ThegetAvailablePlaybackRates
method will return the possible playback rates for the currently playing video. However, if you set thesuggestedRate
parameter to a non-supported integer or float value, the player will round that value down to the nearest supported value in the direction of1
.
-
player. getAvailablePlaybackRates ():Array
- This function returns the set of playback rates in which the current video is available. The default value is
1
, which indicates that the video is playing in normal speed.
The function returns an array of numbers ordered from slowest to fastest playback speed. Even if the player does not support variable playback speeds, the array should always contain at least one value (1
).
Setting playback behavior for playlists
-
player. setLoop (loopPlaylists:Boolean):Void
This function indicates whether the video player should continuously play a playlist or if it should stop playing after the last video in the playlist ends. The default behavior is that playlists do not loop.
This setting will persist even if you load or cue a different playlist, which means that if you load a playlist, call the
setLoop
function with a value oftrue
, and then load a second playlist, the second playlist will also loop.The required
loopPlaylists
parameter identifies the looping behavior.If the parameter value is
true
, then the video player will continuously play playlists. After playing the last video in a playlist, the video player will go back to the beginning of the playlist and play it again.If the parameter value is
false
, then playbacks will end after the video player plays the last video in a playlist.
-
player. setShuffle (shufflePlaylist:Boolean):Void
This function indicates whether a playlist's videos should be shuffled so that they play back in an order different from the one that the playlist creator designated. If you shuffle a playlist after it has already started playing, the list will be reordered while the video that is playing continues to play. The next video that plays will then be selected based on the reordered list.
This setting will not persist if you load or cue a different playlist, which means that if you load a playlist, call the
setShuffle
function, and then load a second playlist, the second playlist will not be shuffled.The required
shufflePlaylist
parameter indicates whether YouTube should shuffle the playlist.If the parameter value is
true
, then YouTube will shuffle the playlist order. If you instruct the function to shuffle a playlist that has already been shuffled, YouTube will shuffle the order again.If the parameter value is
false
, then YouTube will change the playlist order back to its original order.
Playback status
-
player. getVideoLoadedFraction ():Float
- Returns a number between
0
and1
that specifies the percentage of the video that the player shows as buffered. This method returns a more reliable number than the now-deprecatedgetVideoBytesLoaded
andgetVideoBytesTotal
methods.
-
player.getPlayerState():Number
- Returns the state of the player. Возможные значения:
-
-1
– unstarted -
0
– ended -
1
– playing -
2
– paused -
3
– buffering -
5
– video cued
-
-
player. getCurrentTime ():Number
- Returns the elapsed time in seconds since the video started playing.
-
player. getVideoStartBytes ():Number
- Deprecated as of October 31, 2012. Returns the number of bytes the video file started loading from. (This method now always returns a value of
0
.) Example scenario: the user seeks ahead to a point that hasn't loaded yet, and the player makes a new request to play a segment of the video that hasn't loaded yet.
-
player. getVideoBytesLoaded ():Number
- Deprecated as of July 18, 2012. Instead, use the
getVideoLoadedFraction
method to determine the percentage of the video that has buffered.
This method returns a value between0
and1000
that approximates the amount of the video that has been loaded. You could calculate the fraction of the video that has been loaded by dividing thegetVideoBytesLoaded
value by thegetVideoBytesTotal
value.
-
player. getVideoBytesTotal ():Number
- Deprecated as of July 18, 2012. Instead, use the
getVideoLoadedFraction
method to determine the percentage of the video that has buffered.
Returns the size in bytes of the currently loaded/playing video or an approximation of the video's size.
This method always returns a value of1000
. You could calculate the fraction of the video that has been loaded by dividing thegetVideoBytesLoaded
value by thegetVideoBytesTotal
value.
Retrieving video information
-
player. getDuration ():Number
- Returns the duration in seconds of the currently playing video. Note that
getDuration()
will return0
until the video's metadata is loaded, which normally happens just after the video starts playing.
If the currently playing video is a live event , thegetDuration()
function will return the elapsed time since the live video stream began. Specifically, this is the amount of time that the video has streamed without being reset or interrupted. In addition, this duration is commonly longer than the actual event time since streaming may begin before the event's start time.
-
player. getVideoUrl ():String
- Returns the YouTube.com URL for the currently loaded/playing video.
-
player. getVideoEmbedCode ():String
- Returns the embed code for the currently loaded/playing video.
Retrieving playlist information
-
player. getPlaylist ():Array
- This function returns an array of the video IDs in the playlist as they are currently ordered. 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 thegetPlaylist()
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
. Thelistener
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.
События
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 theonReady
andonAutoplayBlocked
events do not specify adata
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 atarget
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 anid
value ofembed-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. Возможные значения:-
-1
(unstarted) -
0
(ended) -
1
(playing) -
2
(paused) -
3
(buffering) -
5
(video cued).
unstarted
(-1
) event. When a video is cued and ready to play, the player will broadcast avideo 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.
Thedata
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. Возможные значения:-
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 thesetPlaybackRate(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 tosetPlaybackRate
.
Thedata
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. ThegetAvailablePlaybackRates
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'sdata
property will specify an integer that identifies the type of error that occurred. Возможные значения:-
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 as101
. It's just a101
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: Currently, the only module that you can set options for is theplayer.getOptions();
captions
module, which handles closed captioning in the player. Upon receiving anonApiChange
event, your application can use the following command to determine which options can be set for thecaptions
module: 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:player.getOptions('captions');
The table below lists the options that the API supports:Retrieving an option: player.getOption(module, option); Setting an option player.setOption(module, option, value);
Модуль Вариант Описание captions fontSize This option adjusts the font size of the captions displayed in the player.
Valid values are-1
,0
,1
,2
, and3
. The default size is0
, 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 above3
will cause the largest caption size to display.captions reload 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 totrue
to reload the closed caption data.
-
onAutoplayBlocked
- This event fires any time the browser blocks autoplay or scripted video playback features, collectively referred to as "autoplay". This includes playback attempted with any of the following player APIs:
-
autoplay
parameter -
loadPlaylist
function -
loadVideoById
function -
loadVideoByUrl
function -
playVideo
function
For complete details, refer to browser-specific policies ( Apple Safari / Webkit , Google Chrome , Mozilla Firefox ) and Mozilla's autoplay guide . -
Примеры
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'ssrc
URL must set theenablejsapi
parameter to1
or the<iframe>
element'senablejsapi
attribute must be set totrue
.The
onPlayerReady
function changes the color of the border around the player to orange when the player is ready. TheonPlayerStateChange
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 thesetVolume
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>
Android WebView Media Integrity API integration
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. The data collected through usage of this API is the app metadata (the package name, version number, and signing certificate) and a device attestation token generated by Google Play services.
The data is used to verify the application and device integrity. It is encrypted, not shared with third parties, and deleted following a fixed retention period. App developers can configure their app identity in the WebView Media Integrity API. The configuration supports an opt-out option.
История изменений
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 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
, andgetAvailableQualityLevels
functions are no longer supported. In particular, calls tosetPlaybackQuality
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 thesuggestedQuality
argument. Similarly, if you call those functions using object syntax, thesuggestedQuality
field is no longer supported. IfsuggestedQuality
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 toDeviceOrientationEvents
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 thecaptions
module and not thecc
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:
-
The new removeEventListener function lets you remove a listener for a specified event.
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 whenplayVideo()
is called. -
The
getVideoStartBytes
method has been deprecated. The method now always returns a value of0
.
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 theonYouTubeIframeAPIReady
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
onPlaybackRateChange
– This event fires when the video's playback rate changes.
-
July 19, 2012
This update contains the following changes:
-
The new
getVideoLoadedFraction
method replaces the now-deprecatedgetVideoBytesLoaded
andgetVideoBytesTotal
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 of5
, 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 namedonYouTubePlayerAPIReady
. 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 anonYouTubePlayerAPIReady
function, both functions will be called, and theonYouTubeIframeAPIReady
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()
anddestroy()
methods. ThesetSize()
method sets the size in pixels of the<iframe>
that contains the player and thedestroy()
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 aninline-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.
The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript.
Using the API's JavaScript functions, you can queue videos for playback; play, pause, or stop those videos; adjust the player volume; or retrieve information about the video being played. You can also add event listeners that will execute in response to certain player events, such as a player state change.
This guide explains how to use the IFrame API. It identifies the different types of events that the API can send and explains how to write event listeners to respond to those events. It also details the different JavaScript functions that you can call to control the video player as well as the player parameters you can use to further customize the player.
Требования
The user's browser must support the HTML5 postMessage
feature. Most modern browsers support 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.
Any web page that uses the IFrame API must also implement the following JavaScript function:
onYouTubeIframeAPIReady
– The API will call this function when the page has finished downloading the JavaScript for the player API, which enables you to then use the API on your page. Thus, this function might create the player objects that you want to display when the page loads.
Начиная
The sample HTML page below creates an embedded player that will load a video, play it for six seconds, and then stop the playback. The numbered comments in the HTML are explained in the list below the example.
<!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>
The following list provides more details about the sample above:
The
<div>
tag in this section identifies the location on the page where the IFrame API will place the video player. The constructor for the player object, which is described in the Loading a video player section, identifies the<div>
tag by itsid
to ensure that the API places the<iframe>
in the proper location. Specifically, the IFrame API will replace the<div>
tag with the<iframe>
tag.As an alternative, you could also put the
<iframe>
element directly on the page. The Loading a video player section explains how to do so.The code in this section loads the IFrame Player API JavaScript code. The example uses DOM modification to download the API code to ensure that the code is retrieved asynchronously. (The
<script>
tag'sasync
attribute, which also enables asynchronous downloads, is not yet supported in all modern browsers as discussed in this Stack Overflow answer .The
onYouTubeIframeAPIReady
function will execute as soon as the player API code downloads. This portion of the code defines a global variable,player
, which refers to the video player you are embedding, and the function then constructs the video player object.The
onPlayerReady
function will execute when theonReady
event fires. In this example, the function indicates that when the video player is ready, it should begin to play.The API will call the
onPlayerStateChange
function when the player's state changes, which may indicate that the player is playing, paused, finished, and so forth. The function indicates that when the player state is1
(playing), the player should play for six seconds and then call thestopVideo
function to stop the video.
Loading a video player
After the API's JavaScript code loads, the API will call the onYouTubeIframeAPIReady
function, at which point you can construct a YT.Player
object to insert a video player on your page. The HTML excerpt below shows the onYouTubeIframeAPIReady
function from the example above:
var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '390', width: '640', videoId: 'M7lc1UVf-VE', playerVars: { 'playsinline': 1 }, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); }
The constructor for the video player specifies the following parameters:
The first parameter specifies either the DOM element or the
id
of the HTML element where the API will insert the<iframe>
tag containing the player.The IFrame API will replace the specified element with the
<iframe>
element containing the player. This 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 aninline-block
element.- The second parameter is an object that specifies player options. The object contains the following properties:
-
width
(number) – The width of the video player. The default value is640
. -
height
(number) – The height of the video player. The default value is390
. -
videoId
(string) – The YouTube video ID that identifies the video that the player will load. -
playerVars
(object) – The object's properties identify player parameters that can be used to customize the player. -
events
(object) – The object's properties identify the events that the API fires and the functions (event listeners) that the API will call when those events occur. In the example, the constructor indicates that theonPlayerReady
function will execute when theonReady
event fires and that theonPlayerStateChange
function will execute when theonStateChange
event fires.
-
As mentioned in the Getting started section, instead of writing an empty <div>
element on your page, which the player API's JavaScript code will then replace with an <iframe>
element, you could create the <iframe>
tag yourself. The first example in the Examples section shows how to do this.
<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>
Note that if you do write the <iframe>
tag, then when you construct the YT.Player
object, you do not need to specify values for the width
and height
, which are specified as attributes of the <iframe>
tag, or the videoId
and player parameters, which are are specified in the src
URL. As an extra security measure, you should also include the origin
parameter to the URL, specifying the URL scheme ( http://
or https://
) and full domain of your host page as the parameter value. While origin
is optional, including it protects against malicious third-party JavaScript being injected into your page and hijacking control of your YouTube player.
For other examples on constructing video player objects, see Examples .
Операции
To call the player API methods, you must first get a reference to the player object you wish to control. You obtain the reference by creating a YT.Player
object as discussed in the Getting started and Loading a video player sections of this document.
Функции
Queueing functions
Queueing functions allow you to load and play a video, a playlist, or another list of videos. If you are using the object syntax described below to call these functions, then you can also queue or load a list of a user's uploaded videos.
The API supports two different syntaxes for calling the queueing functions.
The argument syntax requires function arguments to be listed in a prescribed order.
The object syntax lets you pass an object as a single parameter and to define object properties for the function arguments that you wish to set. In addition, the API may support additional functionality that the argument syntax does not support.
For example, the loadVideoById
function can be called in either of the following ways. Note that the object syntax supports the endSeconds
property, which the argument syntax does not support.
Argument syntax
loadVideoById("bHQqvYy5KYo", 5, "large")
Object syntax
loadVideoById({'videoId': 'bHQqvYy5KYo', 'startSeconds': 5, 'endSeconds': 60});
Queueing functions for videos
-
cueVideoById
Argument syntax
player.cueVideoById(videoId:String, startSeconds:Number):Void
Object syntax
player.cueVideoById({videoId:String, startSeconds:Number, endSeconds:Number}):Void
This function loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until
playVideo()
orseekTo()
is called.- The required
videoId
parameter specifies the YouTube Video ID of the video to be played. In the YouTube Data API, avideo
resource'sid
property specifies the ID. - The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the video should start playing whenplayVideo()
is called. If you specify astartSeconds
value and then callseekTo()
, then the player plays from the time specified in theseekTo()
call. When the video is cued and ready to play, the player will broadcast avideo cued
event (5
). - The optional
endSeconds
parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop playing whenplayVideo()
is called. If you specify anendSeconds
value and then callseekTo()
, theendSeconds
value will no longer be in effect.
loadVideoById
Argument syntax
player.loadVideoById(videoId:String, startSeconds:Number):Void
Object syntax
player.loadVideoById({videoId:String, startSeconds:Number, endSeconds:Number}):Void
This function loads and plays the specified video.
- The required
videoId
parameter specifies the YouTube Video ID of the video to be played. In the YouTube Data API, avideo
resource'sid
property specifies the ID. - The optional
startSeconds
parameter accepts a float/integer. If it is specified, then the video will start from the closest keyframe to the specified time. - The optional
endSeconds
parameter accepts a float/integer. If it is specified, then the video will stop playing at the specified time.
cueVideoByUrl
Argument syntax
player.cueVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void
Object syntax
player.cueVideoByUrl({mediaContentUrl:String, startSeconds:Number, endSeconds:Number}):Void
This function loads the specified video's thumbnail and prepares the player to play the video. The player does not request the FLV until
playVideo()
orseekTo()
is called.- The required
mediaContentUrl
parameter specifies a fully qualified YouTube player URL in the formathttp://www.youtube.com/v/VIDEO_ID?version=3
. - The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the video should start playing whenplayVideo()
is called. If you specifystartSeconds
and then callseekTo()
, then the player plays from the time specified in theseekTo()
call. When the video is cued and ready to play, the player will broadcast avideo cued
event (5). - The optional
endSeconds
parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop playing whenplayVideo()
is called. If you specify anendSeconds
value and then callseekTo()
, theendSeconds
value will no longer be in effect.
loadVideoByUrl
Argument syntax
player.loadVideoByUrl(mediaContentUrl:String, startSeconds:Number):Void
Object syntax
player.loadVideoByUrl({mediaContentUrl:String, startSeconds:Number, endSeconds:Number}):Void
This function loads and plays the specified video.
- The required
mediaContentUrl
parameter specifies a fully qualified YouTube player URL in the formathttp://www.youtube.com/v/VIDEO_ID?version=3
. - The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the video should start playing. IfstartSeconds
(number can be a float) is specified, the video will start from the closest keyframe to the specified time. - The optional
endSeconds
parameter, which is only supported in object syntax, accepts a float/integer and specifies the time when the video should stop playing.
Queueing functions for lists
The cuePlaylist
and loadPlaylist
functions allow you to load and play a playlist. If you are using object syntax to call these functions, you can also queue (or load) a list of a user's uploaded videos.
Since the functions work differently depending on whether they are called using the argument syntax or the object syntax, both calling methods are documented below.
-
cuePlaylist
Argument syntax
Queues the specified playlist. When the playlist is cued and ready to play, the player will broadcast aplayer.cuePlaylist(playlist:String|Array, index:Number, startSeconds:Number):Void
video cued
event (5
).The required
playlist
parameter specifies an array of YouTube video IDs. In the YouTube Data API, thevideo
resource'sid
property identifies that video's ID.The optional
index
parameter specifies the index of the first video in the playlist that will play. The parameter uses a zero-based index, and the default parameter value is0
, so the default behavior is to load and play the first video in the playlist.The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the first video in the playlist should start playing when theplayVideo()
function is called. If you specify astartSeconds
value and then callseekTo()
, then the player plays from the time specified in theseekTo()
call. If you cue a playlist and then call theplayVideoAt()
function, the player will start playing at the beginning of the specified video.
Object syntax
Queues the specified list of videos. The list can be a playlist or a user's uploaded videos feed. The ability to queue a list of search results is deprecated and will no longer be supported as ofplayer.cuePlaylist({listType:String, list:String, index:Number, startSeconds:Number}):Void
15 November 2020 .When the list is cued and ready to play, the player will broadcast a
video cued
event (5
).The optional
listType
property specifies the type of results feed that you are retrieving. Valid values areplaylist
anduser_uploads
. A deprecated value,search
, will no longer be supported as of15 November 2020 . The default value isplaylist
.The required
list
property contains a key that identifies the particular list of videos that YouTube should return.- If the
listType
property value isplaylist
, then thelist
property specifies the playlist ID or an array of video IDs. In the YouTube Data API, theplaylist
resource'sid
property identifies a playlist's ID, and thevideo
resource'sid
property specifies a video ID. - If the
listType
property value isuser_uploads
, then thelist
property identifies the user whose uploaded videos will be returned. - If the
listType
property value issearch
, then thelist
property specifies the search query. Note: This functionality is deprecated and will no longer be supported as of15 November 2020 .
- If the
The optional
index
property specifies the index of the first video in the list that will play. The parameter uses a zero-based index, and the default parameter value is0
, so the default behavior is to load and play the first video in the list.The optional
startSeconds
property accepts a float/integer and specifies the time from which the first video in the list should start playing when theplayVideo()
function is called. If you specify astartSeconds
value and then callseekTo()
, then the player plays from the time specified in theseekTo()
call. If you cue a list and then call theplayVideoAt()
function, the player will start playing at the beginning of the specified video.
-
loadPlaylist
Argument syntax
This function loads the specified playlist and plays it.player.loadPlaylist(playlist:String|Array, index:Number, startSeconds:Number):Void
The required
playlist
parameter specifies an array of YouTube video IDs. In the YouTube Data API, thevideo
resource'sid
property specifies a video ID.The optional
index
parameter specifies the index of the first video in the playlist that will play. The parameter uses a zero-based index, and the default parameter value is0
, so the default behavior is to load and play the first video in the playlist.The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the first video in the playlist should start playing.
Object syntax
This function loads the specified list and plays it. The list can be a playlist or a user's uploaded videos feed. The ability to load a list of search results is deprecated and will no longer be supported as ofplayer.loadPlaylist({list:String, listType:String, index:Number, startSeconds:Number}):Void
15 November 2020 .The optional
listType
property specifies the type of results feed that you are retrieving. Valid values areplaylist
anduser_uploads
. A deprecated value,search
, will no longer be supported as of15 November 2020 . The default value isplaylist
.The required
list
property contains a key that identifies the particular list of videos that YouTube should return.- If the
listType
property value isplaylist
, then thelist
property specifies a playlist ID or an array of video IDs. In the YouTube Data API, theplaylist
resource'sid
property specifies a playlist's ID, and thevideo
resource'sid
property specifies a video ID. - If the
listType
property value isuser_uploads
, then thelist
property identifies the user whose uploaded videos will be returned. - If the
listType
property value issearch
, then thelist
property specifies the search query. Note: This functionality is deprecated and will no longer be supported as of15 November 2020 .
- If the
The optional
index
property specifies the index of the first video in the list that will play. The parameter uses a zero-based index, and the default parameter value is0
, so the default behavior is to load and play the first video in the list.The optional
startSeconds
property accepts a float/integer and specifies the time from which the first video in the list should start playing.
Playback controls and player settings
Воспроизведение видео
-
player. playVideo ():Void
- Plays the currently cued/loaded video. The final player state after this function executes will be
playing
(1).
Note: A playback only counts toward a video's official view count if it is initiated via a native play button in the player.
-
player. pauseVideo ():Void
- Pauses the currently playing video. The final player state after this function executes will be
paused
(2
) unless the player is in theended
(0
) state when the function is called, in which case the player state will not change.
-
player. stopVideo ():Void
- Stops and cancels loading of the current video. This function should be reserved for rare situations when you know that the user will not be watching additional video in the player. If your intent is to pause the video, you should just call the
pauseVideo
function. If you want to change the video that the player is playing, you can call one of the queueing functions without callingstopVideo
first.
Important: Unlike thepauseVideo
function, which leaves the player in thepaused
(2
) state, thestopVideo
function could put the player into any not-playing state, includingended
(0
),paused
(2
),video cued
(5
) orunstarted
(-1
).
-
player. seekTo (seconds:Number, allowSeekAhead:Boolean):Void
- Seeks to a specified time in the video. If the player is paused when the function is called, it will remain paused. If the function is called from another state (
playing
,video cued
, etc.), the player will play the video.The
seconds
parameter identifies the time to which the player should advance.The player will advance to the closest keyframe before that time unless the player has already downloaded the portion of the video to which the user is seeking.
The
allowSeekAhead
parameter determines whether the player will make a new request to the server if theseconds
parameter specifies a time outside of the currently buffered video data.We recommend that you set this parameter to
false
while the user drags the mouse along a video progress bar and then set it totrue
when the user releases the mouse. This approach lets a user scroll to different points of a video without requesting new video streams by scrolling past unbuffered points in the video. When the user releases the mouse button, the player advances to the desired point in the video and requests a new video stream if necessary.
Controlling playback of 360° videos
Note: The 360° video playback experience has limited support on mobile devices. On unsupported devices, 360° videos appear distorted and there is no supported way to change the viewing perspective at all, including through the API, using orientation sensors, or responding to touch/drag actions on the device's screen.
-
player. getSphericalProperties ():Object
- Retrieves properties that describe the viewer's current perspective, or view, for a video playback. Кроме того:
- This object is only populated for 360° videos, which are also called spherical videos.
- If the current video is not a 360° video or if the function is called from a non-supported device, then the function returns an empty object.
- On supported mobile devices, if the
enableOrientationSensor
property is set totrue
, then this function returns an object in which thefov
property contains the correct value and the other properties are set to0
.
Характеристики yaw
A number in the range [0, 360) that 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. The neutral position, facing the center of the video in its equirectangular projection, represents 0°, and this value increases as the viewer turns left. pitch
A number in the range [-90, 90] that 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. The neutral position, facing the center of the video in its equirectangular projection, represents 0°, and this value increases as the viewer looks up. roll
A number in the range [-180, 180] that represents the clockwise or counterclockwise rotational angle of the view in degrees. The neutral position, with the horizontal axis in the equirectangular projection being parallel to the horizontal axis of the view, represents 0°. The value increases as the view rotates clockwise and decreases as the view rotates counterclockwise.
Note that the embedded player does not present a user interface for adjusting the roll of the view. The roll can be adjusted in either of these mutually exclusive ways:- Use the orientation sensor in a mobile browser to provide roll for the view. If the orientation sensor is enabled, then the
getSphericalProperties
function always returns0
as the value of theroll
property. - If the orientation sensor is disabled, set the roll to a nonzero value using this API.
fov
A number in the range [30, 120] that represents the field-of-view of the view in degrees as measured along the longer edge of the viewport. The shorter edge is automatically adjusted to be proportional to the aspect ratio of the view.
The default value is 100 degrees. Decreasing the value is like zooming in on the video content, and increasing the value is like zooming out. This value can be adjusted either by using the API or by using the mousewheel when the video is in fullscreen mode.
-
player. setSphericalProperties (properties:Object):Void
- Sets the video orientation for playback of a 360° video. (If the current video is not spherical, the method is a no-op regardless of the input.)
The player view responds to calls to this method by updating to reflect the values of any known properties in theproperties
object. The view persists values for any other known properties not included in that object.
Кроме того:- If the object contains unknown and/or unexpected properties, the player ignores them.
- As noted at the beginning of this section, the 360° video playback experience is not supported on all mobile devices.
- By default, on supported mobile devices, this function sets only sets the
fov
property and does not affect theyaw
,pitch
, androll
properties for 360° video playbacks. See theenableOrientationSensor
property below for more detail.
properties
object passed to the function contains the following properties:Характеристики yaw
See definition above. pitch
See definition above. roll
See definition above. fov
See definition above. enableOrientationSensor
Note: This property affects the 360° viewing experience on supported devices only. A boolean value that indicates whether the IFrame embed should respond to events that signal changes in a supported device's orientation, such as a mobile browser's DeviceOrientationEvent
. The default parameter value istrue
.
Supported mobile devices- When the value is
true
, an embedded player relies only on the device's movement to adjust theyaw
,pitch
, androll
properties for 360° video playbacks. However, thefov
property can still be changed via the API, and the API is, in fact, the only way to change thefov
property on a mobile device. This is the default behavior. - When the value is
false
, then the device's movement does not affect the 360° viewing experience, and theyaw
,pitch
,roll
, andfov
properties must all be set via the API.
Unsupported mobile devices
TheenableOrientationSensor
property value does not have any effect on the playback experience.
Playing a video in a playlist
-
player. nextVideo ():Void
- This function loads and plays the next video in the playlist.
If
player.nextVideo()
is called while the last video in the playlist is being watched, and the playlist is set to play continuously (loop
), then the player will load and play the first video in the list.If
player.nextVideo()
is called while the last video in the playlist is being watched, and the playlist is not set to play continuously, then playback will end.
-
player. previousVideo ():Void
- This function loads and plays the previous video in the playlist.
If
player.previousVideo()
is called while the first video in the playlist is being watched, and the playlist is set to play continuously (loop
), then the player will load and play the last video in the list.If
player.previousVideo()
is called while the first video in the playlist is being watched, and the playlist is not set to play continuously, then the player will restart the first playlist video from the beginning.
-
player. playVideoAt (index:Number):Void
- This function loads and plays the specified video in the playlist.
The required
index
parameter specifies the index of the video that you want to play in the playlist. The parameter uses a zero-based index, so a value of0
identifies the first video in the list. If you have shuffled the playlist, this function will play the video at the specified position in the shuffled playlist.
Changing the player volume
-
player. mute ():Void
- Mutes the player.
-
player. unMute ():Void
- Unmutes the player.
-
player. isMuted ():Boolean
- Returns
true
if the player is muted,false
if not.
-
player. setVolume (volume:Number):Void
- Sets the volume. Accepts an integer between
0
and100
.
-
player. getVolume ():Number
- Returns the player's current volume, an integer between
0
and100
. Note thatgetVolume()
will return the volume even if the player is muted.
Setting the player size
-
player.setSize(width:Number, height:Number):Object
- Sets the size in pixels of the
<iframe>
that contains the player.
Setting the playback rate
-
player. getPlaybackRate ():Number
- This function retrieves the playback rate of the currently playing video. The default playback rate is
1
, which indicates that the video is playing at normal speed. Playback rates may include values like0.25
,0.5
,1
,1.5
, and2
.
-
player. setPlaybackRate (suggestedRate:Number):Void
- This function sets the suggested playback rate for the current video. If the playback rate changes, it will only change for the video that is already cued or being played. If you set the playback rate for a cued video, that rate will still be in effect when the
playVideo
function is called or the user initiates playback directly through the player controls. In addition, calling functions to cue or load videos or playlists (cueVideoById
,loadVideoById
, etc.) will reset the playback rate to1
.
Calling this function does not guarantee that the playback rate will actually change. However, if the playback rate does change, theonPlaybackRateChange
event will fire, and your code should respond to the event rather than the fact that it called thesetPlaybackRate
function.
ThegetAvailablePlaybackRates
method will return the possible playback rates for the currently playing video. However, if you set thesuggestedRate
parameter to a non-supported integer or float value, the player will round that value down to the nearest supported value in the direction of1
.
-
player. getAvailablePlaybackRates ():Array
- This function returns the set of playback rates in which the current video is available. The default value is
1
, which indicates that the video is playing in normal speed.
The function returns an array of numbers ordered from slowest to fastest playback speed. Even if the player does not support variable playback speeds, the array should always contain at least one value (1
).
Setting playback behavior for playlists
-
player. setLoop (loopPlaylists:Boolean):Void
This function indicates whether the video player should continuously play a playlist or if it should stop playing after the last video in the playlist ends. The default behavior is that playlists do not loop.
This setting will persist even if you load or cue a different playlist, which means that if you load a playlist, call the
setLoop
function with a value oftrue
, and then load a second playlist, the second playlist will also loop.The required
loopPlaylists
parameter identifies the looping behavior.If the parameter value is
true
, then the video player will continuously play playlists. After playing the last video in a playlist, the video player will go back to the beginning of the playlist and play it again.If the parameter value is
false
, then playbacks will end after the video player plays the last video in a playlist.
-
player. setShuffle (shufflePlaylist:Boolean):Void
This function indicates whether a playlist's videos should be shuffled so that they play back in an order different from the one that the playlist creator designated. If you shuffle a playlist after it has already started playing, the list will be reordered while the video that is playing continues to play. The next video that plays will then be selected based on the reordered list.
This setting will not persist if you load or cue a different playlist, which means that if you load a playlist, call the
setShuffle
function, and then load a second playlist, the second playlist will not be shuffled.The required
shufflePlaylist
parameter indicates whether YouTube should shuffle the playlist.If the parameter value is
true
, then YouTube will shuffle the playlist order. If you instruct the function to shuffle a playlist that has already been shuffled, YouTube will shuffle the order again.If the parameter value is
false
, then YouTube will change the playlist order back to its original order.
Playback status
-
player. getVideoLoadedFraction ():Float
- Returns a number between
0
and1
that specifies the percentage of the video that the player shows as buffered. This method returns a more reliable number than the now-deprecatedgetVideoBytesLoaded
andgetVideoBytesTotal
methods.
-
player.getPlayerState():Number
- Returns the state of the player. Возможные значения:
-
-1
– unstarted -
0
– ended -
1
– playing -
2
– paused -
3
– buffering -
5
– video cued
-
-
player. getCurrentTime ():Number
- Returns the elapsed time in seconds since the video started playing.
-
player. getVideoStartBytes ():Number
- Deprecated as of October 31, 2012. Returns the number of bytes the video file started loading from. (This method now always returns a value of
0
.) Example scenario: the user seeks ahead to a point that hasn't loaded yet, and the player makes a new request to play a segment of the video that hasn't loaded yet.
-
player. getVideoBytesLoaded ():Number
- Deprecated as of July 18, 2012. Instead, use the
getVideoLoadedFraction
method to determine the percentage of the video that has buffered.
This method returns a value between0
and1000
that approximates the amount of the video that has been loaded. You could calculate the fraction of the video that has been loaded by dividing thegetVideoBytesLoaded
value by thegetVideoBytesTotal
value.
-
player. getVideoBytesTotal ():Number
- Deprecated as of July 18, 2012. Instead, use the
getVideoLoadedFraction
method to determine the percentage of the video that has buffered.
Returns the size in bytes of the currently loaded/playing video or an approximation of the video's size.
This method always returns a value of1000
. You could calculate the fraction of the video that has been loaded by dividing thegetVideoBytesLoaded
value by thegetVideoBytesTotal
value.
Retrieving video information
-
player. getDuration ():Number
- Returns the duration in seconds of the currently playing video. Note that
getDuration()
will return0
until the video's metadata is loaded, which normally happens just after the video starts playing.
If the currently playing video is a live event , thegetDuration()
function will return the elapsed time since the live video stream began. Specifically, this is the amount of time that the video has streamed without being reset or interrupted. In addition, this duration is commonly longer than the actual event time since streaming may begin before the event's start time.
-
player. getVideoUrl ():String
- Returns the YouTube.com URL for the currently loaded/playing video.
-
player. getVideoEmbedCode ():String
- Returns the embed code for the currently loaded/playing video.
Retrieving playlist information
-
player. getPlaylist ():Array
- This function returns an array of the video IDs in the playlist as they are currently ordered. 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 thegetPlaylist()
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
. Thelistener
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.
События
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 theonReady
andonAutoplayBlocked
events do not specify adata
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 atarget
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 anid
value ofembed-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. Возможные значения:-
-1
(unstarted) -
0
(ended) -
1
(playing) -
2
(paused) -
3
(buffering) -
5
(video cued).
unstarted
(-1
) event. When a video is cued and ready to play, the player will broadcast avideo 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.
Thedata
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. Возможные значения:-
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 thesetPlaybackRate(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 tosetPlaybackRate
.
Thedata
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. ThegetAvailablePlaybackRates
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'sdata
property will specify an integer that identifies the type of error that occurred. Возможные значения:-
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 as101
. It's just a101
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: Currently, the only module that you can set options for is theplayer.getOptions();
captions
module, which handles closed captioning in the player. Upon receiving anonApiChange
event, your application can use the following command to determine which options can be set for thecaptions
module: 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:player.getOptions('captions');
The table below lists the options that the API supports:Retrieving an option: player.getOption(module, option); Setting an option player.setOption(module, option, value);
Модуль Вариант Описание captions fontSize This option adjusts the font size of the captions displayed in the player.
Valid values are-1
,0
,1
,2
, and3
. The default size is0
, 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 above3
will cause the largest caption size to display.captions reload 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 totrue
to reload the closed caption data.
-
onAutoplayBlocked
- This event fires any time the browser blocks autoplay or scripted video playback features, collectively referred to as "autoplay". This includes playback attempted with any of the following player APIs:
-
autoplay
parameter -
loadPlaylist
function -
loadVideoById
function -
loadVideoByUrl
function -
playVideo
function
For complete details, refer to browser-specific policies ( Apple Safari / Webkit , Google Chrome , Mozilla Firefox ) and Mozilla's autoplay guide . -
Примеры
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'ssrc
URL must set theenablejsapi
parameter to1
or the<iframe>
element'senablejsapi
attribute must be set totrue
.The
onPlayerReady
function changes the color of the border around the player to orange when the player is ready. TheonPlayerStateChange
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 thesetVolume
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>
Android WebView Media Integrity API integration
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. The data collected through usage of this API is the app metadata (the package name, version number, and signing certificate) and a device attestation token generated by Google Play services.
The data is used to verify the application and device integrity. It is encrypted, not shared with third parties, and deleted following a fixed retention period. App developers can configure their app identity in the WebView Media Integrity API. The configuration supports an opt-out option.
История изменений
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 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
, andgetAvailableQualityLevels
functions are no longer supported. In particular, calls tosetPlaybackQuality
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 thesuggestedQuality
argument. Similarly, if you call those functions using object syntax, thesuggestedQuality
field is no longer supported. IfsuggestedQuality
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 toDeviceOrientationEvents
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 thecaptions
module and not thecc
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:
-
The new removeEventListener function lets you remove a listener for a specified event.
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 whenplayVideo()
is called. -
The
getVideoStartBytes
method has been deprecated. The method now always returns a value of0
.
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 theonYouTubeIframeAPIReady
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
onPlaybackRateChange
– This event fires when the video's playback rate changes.
-
July 19, 2012
This update contains the following changes:
-
The new
getVideoLoadedFraction
method replaces the now-deprecatedgetVideoBytesLoaded
andgetVideoBytesTotal
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 of5
, 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 namedonYouTubePlayerAPIReady
. 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 anonYouTubePlayerAPIReady
function, both functions will be called, and theonYouTubeIframeAPIReady
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()
anddestroy()
methods. ThesetSize()
method sets the size in pixels of the<iframe>
that contains the player and thedestroy()
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 aninline-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.