21
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Youtube Player API】 YouTube自動再生をコピペで完結

Last updated at Posted at 2019-03-20

#1分でYouTubeのURLを埋め込んで自動再生させる(コピペ)

alt

(一応、【要件】) 表示されたら動画を6秒間再生したあと、動画を停止。

####▼表示させたいviewに下をコピペ

index.html.rb
<div id="player"></div>

####▼表示させたいjsに下をコピペ

application.js

var tag = document.createElement('script');

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('player', {
  height: '360',
  width: '640',
  videoId: 'bjmBJ1Fl0cs',
  events: {
    'onReady': onPlayerReady,
    'onStateChange': onPlayerStateChange
  }
});
}

function onPlayerReady(event) {
  event.target.playVideo();
}

var done = false;
function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.PLAYING && !done) {
    setTimeout(stopVideo, 6000);
    done = true;
  }
}
function stopVideo() {
  player.stopVideo();
}

######うまくできたら下の動画が自動再生される

http://www.youtube.com/watch?v=bjmBJ1Fl0cs
[IMAGE ALT TEXT HERE]
(http://www.youtube.com/watch?v=bjmBJ1Fl0cs)
補足
#####youtubeURL採取方法はこれ
https://bazubu.com/how-to-embed-youtube-to-wp-23776.html

取ってきたURLはだいたいこんな感じ

<iframe width="560" height="315" 
src="https://www.youtube.com/embed/bjmBJ1Fl0cs"
frameborder="0" 
allow="accelerometer; 
autoplay; 
encrypted-media; 
gyroscope; 
picture-in-picture" 
allowfullscreen>
</iframe>

上のコード中のsrc="https://www.youtube.com/embed/bjmBJ1Fl0cs"の中のbjmBJ1Fl0csvideoId : 'ここ';にコピペで色んなYouTubeを自動再生できる

参考記事:https://developers.google.com/youtube/player_parameters?hl=ja
    :http://bashalog.c-brains.jp/15/02/25-100000.php

以上です!

21
17
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?