《親密戲導演》
American Theatre,2018年11月號。
《演員的親密戲》
擷自內文:
「性愛場景,如同設計武打場,或是舞蹈動作一般,需要同樣細心編排的動作設計,特別是在這個 #MeToo時代。 」
「我在研究所時期也是演員,所以我有親身體驗—那種來自同事的不恰當經驗,一起跟我上台的人,或是導演完全不知道該怎麼處理這些(親密戲)場景,所以他們索性就完全不處理。」Sina說 「如果你有一個比較年長的導演,碰到親密戲他會跟你們說:你們就做吧,就試看各種可能。所以你們就開始在性愛場景中即興,這是非常不舒服的經驗,而且大多數時候非常令人受傷。」
「親密戲的指示,從來沒有在演員Emily與她的女搭檔編排動作設計遇到困難時出現(她們當時在編排一個充滿戲劇衝突的雙人愛情戲),即使Emily之前演過同性間的愛情戲,她仍然發現自己舉步維艱, 而她的導演除了不斷對著她們大吼舞臺指示「洶湧的情慾」以外,毫無建樹。兩位演員根本沒有辦法自己演完這場戲,而她們發現到了排練最後階段,她們的導演對著她們大喊「就做吧。時候到了。」
「劇場的一切都是假的,」Sina說,「那是一個由演員搬演的假故事,我們必須永遠記得這點,你不應該因此失去自我,你必須在自我跟所做事情之間取得很好的平衡。是的,你必須把自己奉獻給角色,但你也必須要在適當時候離開。」
.
.
.
.
.
.
.
.
.
前言:
自己日常閱讀時發現這篇文章,其中許多觀念頗為受用,花了幾天翻譯出來,希望能給台灣帶來不同觀念交流、分享,人家對身體以及一切相關觀念,已經好前面了。
雖為英文系畢業,但仍非專業翻譯,謬誤之處歡迎指正。
歡迎轉貼,請勿用做商業用途。
.
.
.
.
.
.
.
.
正文:
Intimate Exchanges
Sex scenes require as much careful choreography as flight or dances, especially in the #MeToo era.
《交換親密》
性愛場景,如同設計武打場,或是舞蹈動作一般,需要同樣細心編排的動作設計,特別是在這個 #MeToo時代。
Adam Noble had been teaching an advanced scene class for just one month when he faced a startling encounter with sexual assault in acting. A student came to him asking for a new scene partner, saying she thought the man she had been working with, on the final scene between Stanley and Blanche in A Streetcar Named Desire, had tried to rape her.
Adam Noble在他的進階場景分析課上遇到一件令他膽戰心驚的表演性騷擾事件,一名學生跟他要求更換場景搭檔,她說她的搭檔企圖在他們一起工作《慾望街車》最後一景Stanley跟Blanche的戲時,企圖強暴她。
Noble immediately offered to serve as a mediator for the two students, who had been rehearsing alone in the young man’s dorm room, in order to clarify what had happened. The situation was resolved as a misunderstanding, and the two were able to continue working together. But for Noble, who had staged his first theatrical flight in 1992, the incident served as a wake-up call.
Noble立即以協調者身分為兩位同學提供幫助(他們一直單獨在男同學宿舍房間單獨排練),以求能夠釐清事實真相。後來發現整起事件其實是個誤會,兩位同學也因此能夠繼續一起順利工作。但對於Noble來說—他從1992年就設計了他的人生第一場舞台打搏鬥戲—這起突發事件有如一記響鐘。
“We were sending these kids off on their own devices with no foundation for how to approach this stuff,” he recalled. The lack of resources for both students and teachers regarding the staging of intimate scenes was apparent.
「我們讓這些孩子在完全不具備如何處理理這種事的相關基礎知識時候,就放手要他們自己發展,」他這麼回憶。「因此,老師與學生雙方都缺乏排練親密戲的必須知識,這件事是顯而易見的。」
Noble developed a method called Extreme Stage Physicality to provide students with a framework to address what he called in an article for The Flight Master maginize “scenarios of intense physicality” with comfort and confidence. He began teaching ESP to high school, undergraduate, nd graduate students across the country. He found that the methodology was effective for all ages, and the number of reported incidents and problems dropped to zero.
Noble後來發展出了一套他稱之為「極端舞台形體」(ESP)的技巧,他對《The Fight Master》雜誌表⽰這個技巧提供了一組完整架構給學生使用,讓他們在「激烈的肢體情境」中可以感到安心並且擁有自信。他開始在高中、大學、研究所教導這套ESP技巧。他發現這套方法適用於所有年齡層,後來這些單位的性騷擾通報數量為零。
“For me as a director, it had to work for aggression, and it had to work for intimacy,” Noble said. “ It had to work across the board for those moments when the body steps in to fill the void, whether it’s violence or intimacy. Theres’s a point where the text and the words are no longer enough and the body steps in. There had to be a way for them to work on it safely.”
「身為導演,我認為在工作時,必須涵蓋侵略性以及親密性這些面向,」Noble說,「這些都必須要被全面地工作到的,特別是在那些時刻,當你的身體必須要介入來填補空缺的時候,會有那麼一個點,光靠文本跟台詞已經不足以支撐而你的身體必須要介入,在這時候必須要有一個安全工作的方法。」
That way would later be referred to as intimacy choreography, a term first used in 2006 by Tonia Sina, creator of the Intimacy Directors International. While studying movement pedagogy, including flowing and mime, Sina was helping to choreograph intimate scenes in student-directed plays and found what she described as “a hole” in choreography and no resources to help with her work.
那套方法,後來被「國際親密戲導演工作坊」創辦人之一Tonia Sina稱為「親密戲形體排練」。當 Sina在鑽研動作教育學時—其中包含小丑與默劇—一面幫忙在學生執導的劇目中擔任動作設計,就在這時候,她發現了在動作設計這個領域中的「空缺」,而這方面,她發現自己完全沒有任何資源可以幫上忙。
For her thesis he created a technique to help actors improve the conditions of their work as well as the results. Published in 2006, “ Intimate Encounters; Staging Intimacy and Sensuality” drew from her own experience as an actor. While attending graduate school at Virginia Commonwealth University, Sina’s personal life was disrupted due to the lack of structure provided for staging intimate sscenes. While rehearsing Picasso at the Latin Agile, she and her acting partner staged a love scene together, alone-a standard practice for such scenarios- with unnerving results.
她在她的論文創造了一套技巧,來幫助演員精進他們工作的狀態以及成果。2006年,她從自身演員經驗出發,發表了《親密接觸:表演中的親密性及其感官性》。大學就讀維吉尼亞聯邦大學時,Sina的私生活就因為沒有一套擁有完整架構的技巧來排演親密場景,而深受其苦。在排練Picasso at the Latin Agile 時,Sina跟她的表演搭擋需要排練一段愛情戲,而且是獨自排練—一個司空見慣的情況—然後最後結果卻令人不安。
“The second our lips touched it was not rehearing,” Sina recalled. “It was just kissing. We both felt it. We both knew. It ended up spiraling. We ended up leaving our parters for a month and we had a showmance. It caused a lot of mayhem in our personal lives because we couldn’t let these characters go. We didn’t have a safe way to do the intimacy, and we didn’t have a safe way of coming out of it.”
「當我們的嘴唇碰在一起時,那就不是在排練了。」Sina回憶道。「那就只是單純在接吻而已。我們都感覺到了,最後越演越烈,我們都因此而跟各自伴侶分手,在那個演出期間我們的私生活真的變得很混亂,因為我們都不肯放下我們劇中角色。我們沒有一個安全的方法來做親密戲,也沒有一個安全的方法來離開它。」
The two dated for a month, but their romantic relationship ended shortly after the show closed. And while Sina’s experience was consensual, there are many cases in which an intimacy director could have prevented non-consensual encounters and abuses of power, especially for young women in the industry.
他們兩個交往了一個月,但隨著戲告一段落感情也就馬上結束了。儘管Sina的案例是當事者雙方都心甘情願,仍然有非常多的例子不是如此,在那樣的狀況下其實親密戲導演是有大把機會可以防止這種違反自身意願的接觸,以及權力的濫用,特別是對業界年輕女性而言。
“While I was in grad school I was also an actress, so I was experiencing it firsthand- situations that had been completely inappropriate from co-workers, people who had been onstage with me, director and there’s a sex scene and they say, ‘You guys just do it. Just try something.’ So you’re improvising a sex scene with your partner. That’s extremely uncomfortable and very victimizing at times.”
「我在研究所時期也是演員,所以我有親身體驗—那種來自同事的不恰當經驗,一起跟我上台的人,或是導演完全不知道該怎麼處理這些(親密戲)場景,所以他們索性就完全不處理。」Sina說 「如果你有一個比較年長的導演,碰到親密戲他會跟你們說:你們就做吧,就試看各種可能。所以你們就開始在性愛場景中即興,這是非常不舒服的經驗,而且大多數時候非常令人受傷。」
Alcoa Rodies, co-founder of Intimacy Directors Internatial, witnessed and was a victim in such scenarios throughout her career. After almost chipping a tooth when a scene partner decided to intensify a kiss onstage, she was told, “ That’s part of the profession. Get used to it.” Knowing there were hundreds of other women who would gladly take her spot in a show if she left, Rodis thought she had to accept that kind of behavior for the rest of her career.
IDI共同創辦人Alcia Rodis在她自己生涯中,親眼見過幾個案例,並且,也曾經有過身為受害者的經驗。在她的對手演員決定在場上把吻戲變得異常激烈時,她的牙齒幾乎都要裂了,儘管如此,她還是被告知「這行就是這樣。早點習慣吧。」因為Rodis清楚知道如果她選擇離開的話,會有其他幾百位女性會搶破頭想要她的位置,她一度以為她必須要在整個職涯中接受這種狀況。
“We sort of learned that’s not the case, and we don’t have to just take it. We can actually be part of the process and work together,” Rodis said.
「我們後來知道其實並不是這樣的,我們不需要逆來順受。我們其實可以在整個工作過程中同心協力地工作。」Rodis 說。
Sina and Rodies, along with co-founder Siobhan Richardson, created the Pillars, the core protocol of IDI’s work and teaching. A codified process, the Pillars consist of Context, Commumication, Consent and Choreography. (They recently estabished a fifth pillar, Closure, to assist actors in walking away from a character after a performance.) Not having this process, Sina said, can be damaging and dangerous.
Sina跟Rodis,以及創辦夥伴Siobhan Richardson發明了「骨幹」這個IDI在工作及教學上的核心要素草案。其中包含:文本、溝通、同意以及動作(近期還加上了第五個骨幹:收尾。來幫助演員在戲結束之後順利離開他的角色。)Sina說,沒有這些幫助的話,是有可能帶來危害的。
“None of it’s real-it’s theatre,” said Sina. “It’s a fake story that is being portrayed by actors, and we have to keep remembering that. You shouldn’t be losing yourself. You need to have some semblance of yourself and some awareness of what you’re doing. Yes you can commit to the character, but you need to come out again.”
「劇場的一切都是假的,」Sina說,「那是一個由演員搬演的假故事,我們必須永遠記得這點,你不應該因此失去自我,你必須在自我跟所做事情之間取得很好的平衡。是的,你必須把自己奉獻給角色,但你也必須要在適當時候離開。」
IDI currently recommends four certified Intimacy Directors, with 16 candidates in training to become certified. Currently only established movement teachers, choreographers, and directors who have worked directly with a founder are able to apply for training. The organization also offers workshops for actors, directors who want to learn basic consent and choreography, and for stage managers and choreographers wanting to learn more about intimacy direction. In August 2018, a 10-day International Intimacy Pedagogy was held in Illinois.
IDI最近推薦了四位經過認證的親密戲導演,陸續還有其他十六位正在培訓。目前,機構只提供專業的、並且曾和創辦者共事過的動作老師、編舞以及導演可以申請接受培訓。IDI有提供工作坊給演員及導演學習「同意」與「動作」的基礎概念,另有舉辦工作坊,給有意願了解更多關於「如何給予親密戲指示」的舞臺經理與動作設計。2018年8月,他們在伊利諾州舉辦了為期10天的國際親密戲教育學工作坊。
Along with the Pillars, another crucial aspect of intimacy directing is recognizing and respecting traumas in one’s colleagues. All IDI-certified choreographers have completed state-offered metal health certification courses.
除了「骨幹」之外,另有一個至關重要的概念:辨識並且尊重同事的創傷。所有IDI的動作設計都完成了由州政府認證的心理健康課程。
“None of us are therapists, and none of us are counselors,” Rodis said. “But we know what to do if someone is having a metal health crisis, and we know what resources to give them. Because of the nature of the work we’re doing, and because some of us are so new, we’re getting further education on trauma.”
「我們都不是心理治療師,我們也都不是諮商師,」Rodis說「但是,我們知道當有人心理出現危機時該給他們什麼資源。因為就我們現在所做的工作本質上來說,我們都是新手,所以我們有必要持續在創傷這個議題上進修。」
While recognizing that theatre professionals are just that- professionals hired to tell a story- the founders also understand that that job can involve actors putting themselves through traumatic experiences night after night.
“We know what you’re doing is different than going to the office every day,” Rodis said, “If you’re playing Lady Macbeth every night, after a while it’s going to wear on you. So we also offer resources on how to close out at the end of every night.”
正因為知道劇場這個職業就是由一群受聘的專業演員來講一則故事,創辦者清楚的認識到這個工作可能需要演員讓他們自己日復一日、夜復一夜的經歷那些創傷。「我們明⽩你的工作不同於朝九晚五的上班族,」Rodis說,「如果妳每天晚上都在飾演馬克白夫人,過一陣子這個角色其實是會影響到妳本人的,正因為如此,我們也提供方法讓你在每晚演出過後把角色給關起來。」
One such resource is the ability to discuss sexuality and sexual experiences openly and without discomfort- a shift from the norm in American culture, which, as actor/director/teacher Claire Warden observed, has little problem with violence but tends to balk when it comes to sex, leaving directors feeling uncomfortable and embarrassed.
其中一個資源,就是擁有能力來討論性以及性經驗而不會感到不適。談論性這件事,不同於具有多重身份(演員、導演與老師)的Claire Warden觀察到的一個美國文化現象:談到暴力時大家都沒問題,不過一但談到性的時候大家都顯得有點畏畏縮縮的,這其實讓導演們都覺得不舒服與尷尬。
“We’ve got this really skewed view of sex and sexuality and intimacy, and an obsession with it,“ Warden Said, “ A lot of shame, judgment, power, and confusion lies around it, which has made it uncomfortable and awkward to talk about openly.” The root problem, she said, may be that “sexuality and intimacy have kind of blurred into one.”
「我們對於性與親密的相關議題有一種扭曲的觀念,同時卻又深深為其著迷」Warden說,「這同時又有許多羞愧、判斷、權力以及困惑參雜其中,因此讓它成為一個公開談論時會帶來不適與尷尬的議題。」根據她說,其實真正根深蒂固的問題是,我們把「性」與「親密」混為一談。
Intimacy direction was never mentioned when an actor we’ll call Emily(not her real name) was performing in a dramatic two-handler and struggled to choreograph a love scene with her female scene partner. Having never performed a same-sex love scene before, Emily found herself at a loss, and her director- whose only technique was to yell the stage direction “Rolling heat!” Repeatedly- was no help. The two actors were unable to stage the scene on their own and found themselves onstage at the end of rehearsal with the director yelling. “Just do it. It’s time.”
親密戲的指導,從來沒有在演員Emily與她的女搭檔編排動作設計遇到困難時出現(她們當時在編排一個充滿戲劇衝突的雙人愛情戲),即使Emily之前演過同性間的愛情戲,她仍然發現自己舉步維艱, 而她的導演除了不斷對著她們大吼舞臺指示「洶湧的情慾」以外,毫無建樹。兩位演員根本沒有辦法自己演完這場戲,而她們發現到了排練最後階段,她們的導演對著她們大喊「就做吧。時候到了。」
Emily recalled that “when it came time to do it in performances, fight director friends of mine ho came to see the how said, ‘That look incredibly uncomfortable for you both. You looked like you were in pain and it was obvious.’’’ Her friends asked her where the intimacy director was. Emily had never heard of such a director, saying, “ I wish I’d known about it at the time when all the yelling was happening.”
Emily後來說,「後來真的演出時,我有個舞台搏鬥導演朋友來看演出,到了所謂的『就做吧』片段時,他說『那看起來對妳們兩個都極其不舒服,妳們看起來超痛苦,而且非常明顯。」她的朋友繼續問她親密戲導演在哪。Emily那時從來沒有聽過有「親密戲導演」這種導演,她說「我真希望在所有的吼叫發叫的當下,我能夠知道『其實有親密戲導演』這件事。」
Emily now a director herself, said she is carful to ensure that her actors are comfortable when staging intimate scenes. “I am hyper-aware of my actors’ sensitivity and I’m constantly checking in with them: ‘Are you okay? Are you comfortable with this? Let me know if you’re not comfortable. We don’t have to do this. We can do something else.’ And my actors thank me for it. They’re not used to that.”
現在身為導演的Emily表示:「在排練親密戲時,我總是對我的演員的感受保持超級高的敏感度,我會不停的詢問他們『你還好嗎?你對這個覺得自在嗎?如果有不舒服要讓我知道。我們不一定要這麼做,我們可以有替代方案的。』我的演員總是對此心存感激,他們對這樣的工作方式其實還不是那麼習慣。」
Uncomfortable situations can present themselves with or without directors in the room. Often scene partners are encouraged to stage the scenes on their own, outside of rehearsal, a practice that can lead to feelings of fear and helplessness. Sina was kissed inappropriately- a kiss that hadn’t been choreographed or rehearsed- in front of an audience of 500 people and had to be in character as she received it.
不舒服的狀況不論導演在不在場都有可能發生。通常演員們會被鼓勵私下自己排練,其實,這麼做很容易引發恐懼與無助感。Sina曾在500位觀眾面前被不當的親吻—一個沒被事先設計或是排練過的吻 —而她在被親的同時還要想辦法讓自己「待在角色裡」。
“There are times where it’s, ‘Kiss, but don’t kiss until previews.’ It’s the worst,” Rodis said. “At best it’s a bad story, at worst they start grabbing you, ‘be in the moment.’ That’s the definition of assault.”
「有時候的情況是親,但是在試演前不會真的親,那種是最糟的。」Rodis說,「當那種狀況發生時,你能得到最好的結果是一個爛故事,最糟的結果是你開始被這件事給抓住還要『待在當下』, 這其實就是侵犯的定義。」
Along with establishing the definition of assault, IDI training also defines consent in clear, unquestionable terms that differentiate between that and permission. A director can give permission to touch another actor, but only a fellow actor can give consent.
除了建立侵犯的定義以外,IDI還以清清楚楚、不容模糊的語彙界定了「同意」與「允許」的差異。 導演可以「允許」演員去觸摸對手,但只有對手演員自己才可以真的表示「同意」。
“The conversation is always very professional and technical, so when we’re talking about parts of the body, it’s the biological name of the part of the body.” said Warden. “And we as intimacy directors never ask anything about and never inquire about the actors’, directors’ or anyone else’s personal sexual life, history, story, proclivities, etc.”
「所有的討論都是非常專業的,當我們必須要談論身體的部位時,我們都會用生物學名稱。」 Warden說,「身為親密戲導演,我們絕對不會去問任何演員、導演或是任何人的個人性愛生活、歷史、故事或是性傾向...等等任何事情。」
The language doesn’t change when the workshops contain students, Warden said, though she may move more slowly.
語彙的使用並不會因為工作坊有學生而改變,Warden說,只是她會教的更慢而已。
“A lot of what we’re saying for adults is still, ‘That is not real. None of this is real.’’’ said Sina. “In rehearsal, we don’t add acting to it until the very last minute, We choreograph it like we do anything else. Just do the moves so everyone knows what’s happening. Then they can add the emotion to it when the actors are ready and they feel they know the choreography well enough. And if you can get that to happen for minors, it separates the sexuality from the choreography and allows them to treat it like it is: choreography.”
「即便我們跟成年人都一直在強調『這都不是真的,這一切都是假的。』」Sina說。「排練的時候,我們不到最後一分鐘是不會加上『表演』的。在最後關頭之前。我們都像是處理其他素材一樣,做形體動作讓大家都知道會發生什麼事。一直到演員們都準備好了,對動作都夠熟悉時,他們才會真的帶入感情去演出。如果你能夠讓這些未成年先開始這麼做,慢慢的所有人就能夠把性跟動作設計分開來來看,然後以正確的眼光看它:動作設計。」
The inability to treat intimate scenes as simply choreography is a problem Sina has observed at numerous drama competitions, where students without sexual experience or knowledge, let alone the ability to separate themselves from the characters they were playing, have performed sex scenes. These situations can be traumatizing for people without the knowledge or resources to handle it.
Sina在無數個戲劇比賽上觀察到一個問題,學生們往無法把親密場景當成動作設計一樣來處理,這群學生們沒有性經驗或是相關知識,想當然就無法在性愛戲中把自己跟扮演的人物切割開來看待。這種狀況是非常有可能讓人受創的,特別是對那些沒有相關知識,或是資源來處理這種狀況的人。
“If they’re not being led through it properly, it can be very, very dangerous,” she said. “It’s illegal in our country to do anything sexual with a minor or have two minors do something sexual in front of an adult. It’s very thin line between choreography and a crime when you’re dealing with minors.”
「如果他們沒有被好好引導的話,那真的非常非常的危險。」她說,「根據我們國家的法律,讓一個或多個未成年人在成年人面前做出帶有性愛意味的事情是違法的。所以面對未成年時,在『動作設計』跟『犯罪』之間其實只有一條非常模糊的線。」
Demand for IDI services and training has spiked in the past year, since the #MeToo movement has exposed abuse in the entertainment field, including theatre, and the issues of consent and empowerment in the workplace (not to mention outside of it) have become central.
自從去年#MeToo運動開始後,對IDI這個機構的服務與訓練來說,他們面臨了重要挑戰。在娛樂產業(包含劇場)的職場上(更別提職場外也是),現在,關於「同意」與「權力」的議題都變得重要無比了。
“At the moment there’s so much need and demand and only so many of us to go around,” Warden said. “I cannot be in every single room and play out there, but what I can do is empower actors or directors or even stag managers to go into a room and say, ‘I would like to offer a way of talking about this.”
「目前來看,親密戲導演的需求與實際從業人數是不成正比的,」Warden說。「很顯然的,我不可能出現在每一個房間裡指導,但我可以做的是賦予演員、導演甚是舞臺經理權力,讓他們能夠在每個房間替自己發聲『我想要提供另外一種工作方式』。」
Also encouraging to Warden is the increased awareness among young students.
對Warden來說,令他欣慰的是年輕一代學生中對這件事情有意識的人數越來越多了。
“My hope, my intentions and my dream is that the next generation of actors, writers, and directors come out with a very different understating of respect and consent with their bodies and each others’ bodies,” Warden said. “And that leads us into an even more free and safe way to creat deep, authentic, risky stories.”
「我的願望、我的本意、以及我的夢想都是下個世代的演員、作家、以及導演都能夠對他們自己以及他人的身體,有一種非常不同於現在的理解、尊重、權利,」Warden說,「這可以讓我們以更自由,同時也更加安全的方式來創造出具深度、真誠、精彩的故事。」
Carey Purcell, New York city-based reporter
aspect of the void 在 YouTube Player API Reference for iframe Embeds 的推薦與評價
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.
RequirementsThe 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.
Getting started
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 its id
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's async
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 the onReady
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 is 1
(playing), the player should play for six seconds and then call the stopVideo
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 an inline-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 is 640
.height
(number) – The height of the video player. The default value is 390
.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 the onPlayerReady
function will execute when the onReady
event fires and that the onPlayerStateChange
function will execute when the onStateChange
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.
OperationsTo 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 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()
or seekTo()
is called.
The required
videoId
parameter specifies the YouTube Video ID of the video to be played. In the YouTube Data API, a video
resource's id
property specifies the ID.The optional
startSeconds
parameter accepts a float/integer and specifies the time from which the video should start playing when playVideo()
is called. If you specify a startSeconds
value and then call seekTo()
, then the player plays from the time specified in the seekTo()
call. When the video is cued and ready to play, the player will broadcast a video 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 when playVideo()
is called. If you specify an endSeconds
value and then call seekTo()
, the endSeconds
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, a video
resource's id
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()
or seekTo()
is called.
The required
mediaContentUrl
parameter specifies a fully qualified YouTube player URL in the format http://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 when playVideo()
is called. If you specify startSeconds
and then call seekTo()
, then the player plays from the time specified in the seekTo()
call. When the video is cued and ready to play, the player will broadcast a video 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 when playVideo()
is called. If you specify an endSeconds
value and then call seekTo()
, the endSeconds
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 format http://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. If startSeconds
(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
player.cuePlaylist(playlist:String|Array,
index:Number,
startSeconds:Number):Void
Queues the specified playlist. When the playlist is cued and ready to play, the player will broadcast a
video cued
event (5
).The required playlist
parameter specifies an array of YouTube video IDs. In the YouTube Data API, the video
resource's id
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 is 0
, 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 the playVideo()
function is called. If you specify a startSeconds
value and then call seekTo()
, then the player plays from the time specified in the seekTo()
call. If you cue a playlist and then call the playVideoAt()
function, the player will start playing at the beginning of the specified video.
Object syntax
player.cuePlaylist({listType:String,
list:String,
index:Number,
startSeconds:Number}):Void
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 of 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 are playlist
and user_uploads
. A deprecated value, search
, will no longer be supported as of 15 November 2020. The default value is playlist
.
The required list
property contains a key that identifies the particular list of videos that YouTube should return.
If the listType
property value is playlist
, then the list
property specifies the playlist ID or an array of video IDs. In the YouTube Data API, the playlist
resource's id
property identifies a playlist's ID, and the video
resource's id
property specifies a video ID.
If the listType
property value is user_uploads
, then the list
property identifies the user whose uploaded videos will be returned.
If the listType
property value is search
, then the list
property specifies the search query. Note: This functionality is deprecated and will no longer be supported as of 15 November 2020.
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 is 0
, 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 the playVideo()
function is called. If you specify a startSeconds
value and then call seekTo()
, then the player plays from the time specified in the seekTo()
call. If you cue a list and then call the playVideoAt()
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, the video
resource's id
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 is 0
, 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 of 15 November 2020.
player.loadPlaylist({list:String,
listType:String,
index:Number,
startSeconds:Number}):Void
The optional listType
property specifies the type of results feed that you are retrieving. Valid values are playlist
and user_uploads
. A deprecated value, search
, will no longer be supported as of 15 November 2020. The default value is playlist
.
The required list
property contains a key that identifies the particular list of videos that YouTube should return.
If the listType
property value is playlist
, then the list
property specifies a playlist ID or an array of video IDs. In the YouTube Data API, the playlist
resource's id
property specifies a playlist's ID, and the video
resource's id
property specifies a video ID.
If the listType
property value is user_uploads
, then the list
property identifies the user whose uploaded videos will be returned.
If the listType
property value is search
, then the list
property specifies the search query. Note: This functionality is deprecated and will no longer be supported as of 15 November 2020.
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 is 0
, 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
Playing a video
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 the ended
(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 calling stopVideo
first.Important: Unlike the
pauseVideo
function, which leaves the player in the paused
(2
) state, the stopVideo
function could put the player into any not-playing state, including ended
(0
), paused
(2
), video cued
(5
) or unstarted
(-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 the seconds
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 to true
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. In addition:
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 to true
, then this function returns an object in which the fov
property contains the correct value and the other properties are set to 0
.The object contains the following properties:
Properties
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 returns 0
as the value of the roll
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 the
properties
object. The view persists values for any other known properties not included in that object.In addition:
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 the yaw
, pitch
, and roll
properties for 360° video playbacks. See the enableOrientationSensor
property below for more detail.The
properties
object passed to the function contains the following properties: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 is true
.Supported mobile devices
When the value is
true
, an embedded player relies only on the device's movement to adjust the yaw
, pitch
, and roll
properties for 360° video playbacks. However, the fov
property can still be changed via the API, and the API is, in fact, the only way to change the fov
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 the yaw
, pitch
, roll
, and fov
properties must all be set via the API.Unsupported mobile devices
The
enableOrientationSensor
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 of 0
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
and 100
.player.getVolume():Number
Returns the player's current volume, an integer between
0
and 100
. Note that getVolume()
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 like 0.25
, 0.5
, 1
, 1.5
, and 2
.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 to 1
.Calling this function does not guarantee that the playback rate will actually change. However, if the playback rate does change, the
onPlaybackRateChange
event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackRate
function.The
getAvailablePlaybackRates
method will return the possible playback rates for the currently playing video. However, if you set the suggestedRate
parameter to a non-supported integer or float value, the player will round that value down to the nearest supported value in the direction of 1
.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 of true
, 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
and 1
that specifies the percentage of the video that the player shows as buffered. This method returns a more reliable number than the now-deprecated getVideoBytesLoaded
and getVideoBytesTotal
methods.player.getPlayerState():Number
Returns the state of the player. Possible values are:
-1
– unstarted0
– ended1
– playing2
– paused3
– buffering5
– video cuedplayer.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 between
0
and 1000
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 the getVideoBytesLoaded
value by the getVideoBytesTotal
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 of
1000
. You could calculate the fraction of the video that has been loaded by dividing the getVideoBytesLoaded
value by the getVideoBytesTotal
value.Retrieving video information
player.getDuration():Number
Returns the duration in seconds of the currently playing video. Note that
getDuration()
will return 0
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, the
getDuration()
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 the getPlaylist()
function's return value will reflect the shuffled order.player.getPlaylistIndex():Number
This function returns the index of the playlist video that is currently playing.
If you have not shuffled the playlist, the return value will identify the position where the playlist creator placed the video. The return value uses a zero-based index, so a value of 0
identifies the first video in the playlist.
If you have shuffled the playlist, the return value will identify the video's order within the shuffled playlist.
Adding or removing an event listener
player.addEventListener(event:String, listener:String):Void
Adds a listener function for the specified
event
. The Events section below identifies the different events that the player might fire. The listener is a string that specifies the function that will execute when the specified event fires.player.removeEventListener(event:String, listener:String):Void
Removes a listener function for the specified
event
. The listener
is a string that identifies the function that will no longer execute when the specified event fires.Accessing and modifying DOM nodes
player.getIframe():Object
This method returns the DOM node for the embedded
<iframe>
.player.destroy():Void
Removes the
<iframe>
containing the player.Events
The API fires events to notify your application of changes to the embedded player. As noted in the previous section, you can subscribe to events by adding an event listener when constructing the YT.Player
object, and you can also use the addEventListener
function.
The API will pass an event object as the sole argument to each of those functions. The event object has the following properties:
The event's
target
identifies the video player that corresponds to the event.The event's
data
specifies a value relevant to the event. Note that the onReady
and onAutoplayBlocked
events do not specify a data
property.The following list defines the events that the API fires:
onReady
This event fires whenever a player has finished loading and is ready to begin receiving API calls. Your application should implement this function if you want to automatically execute certain operations, such as playing the video or displaying information about the video, as soon as the player is ready.
The example below shows a sample function for handling this event. The event object that the API passes to the function has a
target
property, which identifies the player. The function retrieves the embed code for the currently loaded video, starts to play the video, and displays the embed code in the page element that has an id
value of embed-code
.
function onPlayerReady(event) {
var embedCode = event.target.getVideoEmbedCode();
event.target.playVideo();
if (document.getElementById('embed-code')) {
document.getElementById('embed-code').innerHTML = embedCode;
}
}
onStateChange
This event fires whenever the player's state changes.
The
data
property of the event object that the API passes to your event listener function will specify an integer that corresponds to the new player state.Possible values are:
-1
(unstarted)
0
(ended)
1
(playing)
2
(paused)
3
(buffering)
5
(video cued).
When the player first loads a video, it will broadcast an
unstarted
(-1
) event. When a video is cued and ready to play, the player will broadcast a video cued
(5
) event. In your code, you can specify the integer values or you can use one of the following namespaced variables:
YT.PlayerState.ENDED
YT.PlayerState.PLAYING
YT.PlayerState.PAUSED
YT.PlayerState.BUFFERING
YT.PlayerState.CUED
onPlaybackQualityChange
This event fires whenever the video playback quality changes. It might signal a change in the viewer's playback
environment. See the YouTube Help Center for more
information about factors that affect playback conditions or that might cause the event to fire.
The
data
property value of the event object that the API passes to the event listener function will be a string that identifies the new playback quality.Possible values are:
small
medium
large
hd720
hd1080
highres
onPlaybackRateChange
This event fires whenever the video playback rate changes. For example, if you call the
setPlaybackRate(suggestedRate)
function, this event will fire if the playback rate actually changes. Your application should respond to the event and should not assume that the playback rate will automatically change when the setPlaybackRate(suggestedRate)
function is called. Similarly, your code should not assume that the video playback rate will only change as a result of an explicit call to setPlaybackRate
.The
data
property value of the event object that the API passes to the event listener function will be a number that identifies the new playback rate.The
getAvailablePlaybackRates
method returns a list of the valid playback rates for the currently cued or playing video.onError
This event fires if an error occurs in the player.
The API will pass an
event
object to the event listener function. That object's data
property will specify an integer that identifies the type of error that occurred. Possible values are:
2
– The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks. 5
– The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred. 100
– The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.
101
– The owner of the requested video does not allow it to be played in embedded players.
150
– This error is the same as 101
. It's just a 101
error in disguise!
onApiChange
This event is fired to indicate that the player has loaded (or unloaded) a module with exposed API methods. Your application can listen for this event and then poll the player to determine which options are exposed for the recently loaded module. Your application can then retrieve or update the existing settings for those options.
The following command retrieves an array of module names for which you can set player options:
player.getOptions();
Currently, the only module that you can set options for is the
captions
module, which handles closed captioning in the player. Upon receiving an onApiChange
event, your application can use the following command to determine which options can be set for the captions
module:player.getOptions('captions');
By polling the player with this command, you can confirm that the options you want to access are, indeed, accessible. The following commands retrieve and update module options:
Retrieving an option:The table below lists the options that the API supports:
player.getOption(module, option);Setting an option
player.setOption(module, option, value);
Module
Option
Description
captions
fontSize
This option adjusts the font size of the captions displayed in the player.
Valid values are
-1
, 0
, 1
, 2
, and 3
. The default size is 0
, and the smallest size is -1
. Setting this option to an integer below -1
will cause the smallest caption size to display, while setting this option to an integer above 3
will cause the largest caption size to display.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 to true
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
Most browsers have policies that can block autoplay in desktop, mobile, and other
environments if certain conditions are true. Instances where this policy may be triggered
include unmuted playback without user
interaction, or when a Permissions Policy
to permit autoplay on a cross-origin iframe has not been set.
For complete details, refer to browser-specific policies
(Apple Safari / Webkit,
Google Chrome,
Mozilla Firefox)
and Mozilla's autoplay guide.
Examples
Creating
YT.Player
objectsExample 1: Use API with existing <iframe>
In this example, an <iframe>
element on the page already defines the player with which the API will be used. Note that either the player's src
URL must set the enablejsapi
parameter to 1
or the <iframe>
element's enablejsapi
attribute must be set to true
.
The onPlayerReady
function changes the color of the border around the player to orange when the player is ready. The onPlayerStateChange
function then changes the color of the border around the player based on the current player status. For example, the color is green when the player is playing, red when paused, blue when buffering, and so forth.
This example uses the following code:
<iframe id="existing-iframe-example"
width="640" height="360"
src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
frameborder="0"
style="border: solid 4px #37474F"
></iframe><script type="text/javascript">
var tag = document.createElement('script');
tag.id = 'iframe-demo';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('existing-iframe-example', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
document.getElementById('existing-iframe-example').style.borderColor = '#FF6D00';
}
function changeBorderColor(playerStatus) {
var color;
if (playerStatus == -1) {
color = "#37474F"; // unstarted = gray
} else if (playerStatus == 0) {
color = "#FFFF00"; // ended = yellow
} else if (playerStatus == 1) {
color = "#33691E"; // playing = green
} else if (playerStatus == 2) {
color = "#DD2C00"; // paused = red
} else if (playerStatus == 3) {
color = "#AA00FF"; // buffering = purple
} else if (playerStatus == 5) {
color = "#FF6DOO"; // video cued = orange
}
if (color) {
document.getElementById('existing-iframe-example').style.borderColor = color;
}
}
function onPlayerStateChange(event) {
changeBorderColor(event.data);
}
</script>
Example 2: Loud playback
This example creates a 1280px by 720px video player. The event listener for the onReady
event then calls the setVolume
function to adjust the volume to the highest setting.
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('player', {
width: 1280,
height: 720,
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': onPlayerError
}
});
}function onPlayerReady(event) {
event.target.setVolume(100);
event.target.playVideo();
}
Example 3: This example sets player parameters to automatically play the video when it loads and to hide the video player's controls. It also adds event listeners for several events that the API broadcasts.
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('player', {
videoId: 'M7lc1UVf-VE',
playerVars: { 'autoplay': 1, 'controls': 0 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': onPlayerError
}
});
}
Controlling 360° videos
This example uses the following code:
<style>Android WebView Media Integrity API integration
.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>
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.
Revision history
June 24, 2024
The documentation has been updated to note that YouTube has extended the
Android WebView Media Integrity API
to enable embedded media players, including YouTube player embeds in Android applications, to
verify the embedding app's authenticity. With this change, embedding apps automatically send an
attested app ID to YouTube.
November 20, 2023
The new onAutoplayBlocked
event API is now available.
This event notifies your application if the browser blocks autoplay or scripted playback.
Verification of autoplay success or failure is an
established paradigm
for HTMLMediaElements, and the onAutoplayBlocked
event now provides similar
functionality for the IFrame Player API.
April 27, 2021
The Getting Started and Loading a Video Player sections have been updated to include examples of using a playerVars
object to customize the player.
October 13, 2020
Note: This is a deprecation announcement for the embedded player
functionality that lets you configure the player to load search results. This announcement affects
the IFrame Player API's queueing functions for lists,
cuePlaylist
and
loadPlaylist
.
This change will become effective on or after 15 November 2020. After that time, calls to the
cuePlaylist
or loadPlaylist
functions that set the listType
property to search
will generate a 4xx
response code, such as
404
(Not Found
) or 410
(Gone
). This change
also affects the list
property for those functions as that property no longer
supports the ability to specify a search query.
As an alternative, you can use the YouTube Data API's
search.list
method to retrieve search
results and then load selected videos in the player.
October 24, 2019
The documentation has been updated to reflect the fact that the API no longer supports functions for setting or retrieving playback quality.
As explained in this YouTube Help Center article, to give you the best viewing
experience, YouTube adjusts the quality of your video stream based on your viewing conditions.
The changes explained below have been in effect for more than one year. This update merely aligns
the documentation with current functionality:
The
getPlaybackQuality
, setPlaybackQuality
, and getAvailableQualityLevels
functionsare no longer supported. In particular, calls to
setPlaybackQuality
will be no-op functions, meaning they willnot actually have any impact on the viewer's playback experience.
The queueing functions for videos and playlists --
cueVideoById
,loadVideoById
, etc. -- no longer support the suggestedQuality
argument.Similarly, if you call those functions using object syntax, the
suggestedQuality
field is no longer supported.If
suggestedQuality
is specified, it will be ignored when the request is handled. It will not generate anywarnings or errors.
The
onPlaybackQualityChange
event is still supported and might signal achange in the viewer's playback environment. See the Help Center article
referenced above for more information about factors that affect playback conditions or that might cause the event to fire.
May 16, 2018
The API now supports features that allow users (or embedders) to control the viewing perspective for 360° videos:
The
getSphericalProperties
function retrieves the current orientation for the video playback. The orientation includes the following data:yaw - represents the horizontal angle of the view in degrees, which reflects the extent to which the user turns the view to face further left or right
pitch - represents the vertical angle of the view in degrees, which reflects the extent to which the user adjusts the view to look up or down
roll - represents the rotational angle (clockwise or counterclockwise) of the view in degrees.
fov - represents the field-of-view of the view in degrees, which reflects the extent to which the user zooms in or out on the video.
The
setSphericalProperties
function modifies the view to match the submitted property values. In addition to the orientation values described above, this function supports a Boolean field that indicates whether the IFrame embed should respond to DeviceOrientationEvents
on supported mobile devices.This example demonstrates and lets you test these new features.
June 19, 2017
This update contains the following changes:
Documentation for the YouTube Flash Player API and YouTube JavaScript Player API has been removed and redirected to this document. The deprecation announcement for the Flash and JavaScript players was made on January 27, 2015. If you haven't done so already, please migrate your applications to use IFrame embeds and the IFrame Player API.
August 11, 2016
This update contains the following changes:
The newly published YouTube API Services Terms of Service ("the Updated Terms"), discussed in detail on the YouTube Engineering and Developers Blog, provides a rich set of updates to the current Terms of Service. In addition to the Updated Terms, which will go into effect as of February 10, 2017, this update includes several supporting documents to help explain the policies that developers must follow.
The full set of new documents is described in the revision history for the Updated Terms. In addition, future changes to the Updated Terms or to those supporting documents will also be explained in that revision history. You can subscribe to an RSS feed listing changes in that revision history from a link in that document.
June 29, 2016
This update contains the following changes:
The documentation has been corrected to note that the onApiChange
method provides access to the captions
module and not the cc
module.
June 24, 2016
The Examples section has been updated to include an example that demonstrates how to use the API with an existing <iframe>
element.
January 6, 2016
The clearVideo
function has been deprecated and removed from the documentation. The function no longer has any effect in the YouTube player.
December 18, 2015
European Union (EU) laws require that certain disclosures must be given to and consents obtained from end users in the EU. Therefore, for end users in the European Union, you must comply with the EU User Consent Policy. We have added a notice of this requirement in our YouTube API Terms of Service.
April 28, 2014
This update contains the following changes:
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 when playVideo()
is called.
The getVideoStartBytes
method has been deprecated. The method now always returns a value of 0
.
August 22, 2012
This update contains the following changes:
The example in the Loading a video player section that demonstrates how to manually create the <iframe>
tag has been updated to include a closing </iframe>
tag since the onYouTubeIframeAPIReady
function is only called if the closing </iframe>
element is present.
August 6, 2012
This update contains the following changes:
The Operations section has been expanded to list all of the supported API functions rather than linking to the JavaScript Player API Reference for that list.
The API supports several new functions and one new event that can be used to control the video playback speed:
Functions
getAvailablePlaybackRates
– Retrieve the supported playback rates for the cued or playing video. Note that variable playback rates are currently only supported in the HTML5 player.
getPlaybackRate
– Retrieve the playback rate for the cued or playing video.
setPlaybackRate
– Set the playback rate for the cued or playing video.
Events
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-deprecated getVideoBytesLoaded
and getVideoBytesTotal
methods. The new method returns the percentage of the video that the player shows as buffered.
The onError
event may now return an error code of 5
, which indicates that the requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.
The Requirements section has been updated to indicate that any web page using the IFrame API must also implement the onYouTubeIframeAPIReady
function. Previously, the section indicated that the required function was named onYouTubePlayerAPIReady
. Code samples throughout the document have also been updated to use the new name.
Note: To ensure that this change does not break existing implementations, both names will work. If, for some reason, your page has an onYouTubeIframeAPIReady
function and an onYouTubePlayerAPIReady
function, both functions will be called, and the onYouTubeIframeAPIReady
function will be called first.
The code sample in the Getting started section has been updated to reflect that the URL for the IFrame Player API code has changed to http://www.youtube.com/iframe_api
. To ensure that this change does not affect existing implementations, the old URL (http://www.youtube.com/player_api
) will continue to work.
July 16, 2012
This update contains the following changes:
The Operations section now explains that the API supports the setSize()
and destroy()
methods. The setSize()
method sets the size in pixels of the <iframe>
that contains the player and the destroy()
method removes the <iframe>
.
June 6, 2012
This update contains the following changes:
We have removed the experimental
status from the IFrame Player API.
The Loading a video player section has been updated to point out that when inserting the <iframe>
element that will contain the YouTube player, the IFrame API replaces the element specified in the constructor for the YouTube player. This documentation change does not reflect a change in the API and is intended solely to clarify existing behavior.
In addition, that section now notes that the insertion of the <iframe>
element could affect the layout of your page if the element being replaced has a different display style than the inserted <iframe>
element. By default, an <iframe>
displays as an inline-block
element.
March 30, 2012
This update contains the following changes:
The Operations section has been updated to explain that the IFrame API supports a new method, getIframe()
, which returns the DOM node for the IFrame embed.
March 26, 2012
This update contains the following changes:
The Requirements section has been updated to note the minimum player size.
... <看更多>
aspect of the void 在 get value of actual parameter that has an annotation, or find ... 的推薦與評價
... <看更多>