Youtube autoplay not working on mobile devices with embedded HTML5 player
Asked Answered
E

6

75

To my problem, I have one link <a href="http://www.youtube.com/embed/YT-ID" class="overlay_video"></a>. I want to play the video by clicking the link in a fancybox overlay window. This is not a problem. The problem is the parameters, for example "autoplay" or "autohide".

The following link doesn't work:

<a href="http://www.youtube.com/embed/YT-ID?autoplay=1" class="overlay_video"></a>

The Overlay-Window opened, but the video is not playing automatically.

EDIT: I want to use the HTML5 Player on mobile devices. On a desktop-browser it works with the parameters, but not on mobile devices.

Eben answered 26/2, 2013 at 13:48 Comment(4)
The problem must be somewhere else, as your syntax is exactly as in the fancybox demo: <a class="various iframe" href="http://www.youtube.com/embed/L9szn1QQfas?autoplay=1">Youtube (iframe)</a> And there is no problem with autoplay. How do you invoke the fancybox?Jilli
To invoke the fancybox, i use a standard snippet, for example $(".overlay_video").fancybox({ 'width' : 95%, [..] 'type' : 'iframe' });Eben
I have forgot a small detail. New Infos in the description. Sorry.Eben
Oh this changes a lot :D According to the Youtube API the autoplay parameter also works for the HTML5 Player. What device are you using?Jilli
J
74

As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.

See https://mcmap.net/q/122341/-youtube-embedded-video-autoplay-feature-not-working-in-iphone and https://mcmap.net/q/122441/-autoplay-audio-files-on-an-ipad-with-html5

Jilli answered 26/2, 2013 at 15:41 Comment(6)
Thank you :) I will test it later on my android tablet.Eben
By the way - the other parameters, like autohide or rel are fully functional. :)Eben
Yeah, because Apple wants to avoid eventually unnecessary traffic on their mobile devices - that affects only the autoplay functionality ;)Jilli
I understand ;) ok, android (4.2.2) does the same.Eben
This is incorrect. It can be done on iOS see my answer further below.Mccain
For the future me or anybody else, the autoplay works ONLY IF the video is muted AND YOUR PHONE IS NOT ON POWER SAVING MODE.Viator
S
21

Have a look on code below. Tested and found working on Mobile and Tablet devices.

<!-- 1. The <iframe> (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',
      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>
Sayles answered 25/11, 2016 at 7:20 Comment(6)
Hi! I've tried your code and it actually works! Well done! However, I've found an exeption in Safari 8 on iPad which starts to load the video and never ends unless you stop and then play it. Does somebody have any suggestions? (Trigger pause and play using setTimeout doesn't work...)Strigose
It seems like there has been an update to iOS that requires you to mute the video before you play it, if you want it to autoplay. if you would call event.target.mute(); right before event.target.playVideo(); you should be good.Serviceable
With this solution I managed to autoplay youtube on latest safari OS high Sierra but not much luck on iphone.Antinomy
While this works for the youtube video that you have used in this example, it does not work for the youtube video i pointed to. I get this error: Refused to execute script from <theurliused.com> because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.Ascent
This wont work if you add sometype of event handler to it.. for example adding a button that would open the video.. you can see example here on your device -> codepen.io/Digggid/pen/QRZjgJ?editors=1010Cromlech
Add event.target.mute(); to onPlayerReady before the playVideo to make it works also at IOS, also make sure playsinline=1. Note: I was needed to send the playsinline=1 also at the video URL parametersCooe
M
16

The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
    </head>
  <body>
<!-- 1. The <iframe> (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', {
      width: '100%',
      videoId: 'osz5tVY97dQ',
      playerVars: { 'autoplay': 1, 'playsinline': 1 },
      events: {
        'onReady': onPlayerReady
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
     event.target.mute();
    event.target.playVideo();
  }
</script>
  </body>
</html>
Mccain answered 10/12, 2019 at 12:38 Comment(4)
This solution does work. I am finding a weird issue with it though. My devices will not turn off due to inactivity with this solution. It's as if every time .playVideo() runs it may be keeping my device from timing out due to inactivity (which is wanted to save battery life). Can you confirm this and possibly offer another solution?Coronation
@4ndy, but is this an issue? I mean, if I opened a video to watch (whether it autoplays or not), I wouldn't want my device's screen to turn off due to inactivity while I am watching the video.Hypercriticism
it works only when its in muteFillister
and only when the device is not on power saving modeViator
C
7

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

Reference: https://developers.google.com/youtube/iframe_api_reference

Carrell answered 19/8, 2020 at 11:59 Comment(2)
It can be played automatically if video is muted.Climax
@Climax how???Opuntia
K
1

There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.

Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.

Koerlin answered 9/1, 2016 at 7:15 Comment(1)
Thank you for your comment. This way is for any - i named - customer user - but not a way for any "standard" customer.Eben
S
-1

How to use a Youtube channel live url to embed and autoplay. Instead of Video ID that has to be constantly updated for live stream changes.

I mixed two sets of code and came up with a working auto play Youtube video embed from a channel live stream.

My thanks to both of the other contributors for their help. Hopefully this helps someone else some time.

Example stream https://www.youtube.com/embed/live_stream?channel=UCwobzUc3z-0PrFpoRxNszXQ

The code below by Zubi answered Nov 25 '16 at 7:20 works with Youtube videos.

With code by Darien Chaffart found at

https://mcmap.net/q/270642/-js-code-to-pull-youtube-livestream-video-id

Example

<html>
<head>



</head>
<body>
<center>



<script src="https://www.youtube.com/iframe_api"></script>

<!-- Insert Livestream Video -->
<iframe id="live-video" src="https://www.youtube.com/embed/live_stream?channel=UCwobzUc3z-0PrFpoRxNszXQ&enablejsapi=1" width="100%" height="100%" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen enablejsapi="1"></iframe>

<!-- Basic API code for Youtube videos -->
<script>
  var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('live-video', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}
function onPlayerReady() {
  var url = player.getVideoUrl(); /*Use Youtube API to pull Video URL*/
  var match = url.match(/[?&]v=([^&]+)/);
  var videoId = match[1]; /*Use regex to determine exact Video URL*/
  // Insert a new iFrame for the livestream chat after a specific div named chatframe*/
  var livevid = document.createElement("iframe");
  livevid.src = 'https://www.youtube.com/live_chat?v=' + videoId + ''
  livevid.width = '100%';
  livevid.height= '100%';
  document.getElementById("chatframe").appendChild(livevid);
}
    function onPlayerStateChange() {
    }

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

    // 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, 90000000);
        done = true;
      }
    }
    function stopVideo() {
      player.stopVideo();
    }
       
</script>



</center>
</body>
</html>
Synaeresis answered 15/12, 2021 at 16:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.