Custom play-button trips on iOS video autoplay restriction - ios

Video autoplay (including YouTubes autoplay=1) does not work on iOS Safari. That is thourougly documented by both Apple and a large number of blog posts.
This does however cause a problem with using custom controls for YouTube videos, that I can't find a definate yes/no answer for anywhere.
If I used a simple HTML5 video tag there would be no issue - but I would really rather not have to encode all the videos for all the different platforms.
What I need to accomplish is:
A cover image is shown (flat PNG with a play icon on top).
The user clicks the cover image, the image is replaced by a YouTube video that starts playing.
This is not autoplay from the users perspective, since it is initiated by a click. However on all non-Flash devices YouTube embeds are displayed in an iframe, causing the video to effectively be loaded and autoplayed (or at least, I think so).
Does anyone know of any workarounds for this problem?
This snippet illustrates the problem. It works in e.g. FireFox, but on iOS Safari it simple shows the loading indicator and then ends in a black screen.
If I add the "apple-mobile-web-app-capable" meta tag and fire up the site from the home screen, the videos play correctly.
<div id="movieContainer" style="width: 768px; height: 432px; border: 1px solid #cccccc;">Initializing player API...</div>
<div id="status">Initializing player API...</div>
<button onclick="player.playVideo();">Play</button>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var playerAPIIsLoaded = false;
function onYouTubePlayerAPIReady()
{
playerAPIIsLoaded = true;
document.getElementById("status").innerHTML = "Player API initialized!";
}
var player = null;
function initMovie()
{
document.getElementById("status").innerHTML = "Loading video..."
player = new YT.Player(
'movieContainer',
{
height: '432'
, width: '768'
, playerVars: { 'autoplay': 0, 'controls': 2, 'rel': 0, 'showinfo': 0 }
, videoId: 'MwnZr4VJQPQ'
, events: { 'onReady': function (event) { document.getElementById("status").innerHTML = "Video loaded!";/*event.target.playVideo();*/ } }
}
);
}
window.onload = initMovie;
</script>

Related

How can I remove the hover effect of progress bar on youtube embedded player?

I have embedded a youtube video in my HTML page. Since the video screen size is too small, the hover effect on the progress bar is getting cropped.
How can I stop this hover effect on the progress bar?
There is no option to disable the thumbnail preview in YouTube's native embed players. But you can disable the player controls altogether by appending ?controls=0 to the embed URL.
Here is an example, <iframe width='340' height='200' src="https://www.youtube.com/embed/MpGLUVbqoYQ?controls=0"></iframe>
the previous comment has it right. if youre using the API with javascript it might be best to use it like this:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'videoId',
playerVars: {
'controls': 0
}
});
}

youtube-iframe-api remove suggestion thumbnails at bottom of video

Could somebody tell me how to remove youtube suggestion thumbnails on embedded video.
I am using iframe api. It feel like it should be easy. But i just can't find anything on google on how to do it.
tag.src = "https://www.youtube.com/iframe_api";
function initPLayer(playerDivId){
return new YT.Player(playerDivId, {
height: '390',
width: '640',
videoId: '4EDMR75lrKY',
events: {
'onReady': onPlayerReady1,
'onStateChange': onPlayerStateChangePlayer1
}
});
}
Thanks for help!
I knew it was obvious :P.
There is thing called player parameters.
Rel:
This parameter indicates whether the player should show related videos when playback of the initial video ends. Supported values are 0 and 1. The default value is 1.

How to get HTML5 video thumbnail without using poster on safari or iOS?

I have embedded HTML5 video with mp4 format. How to get thumbnail image like poster without using "poster" attribute. This problem coming on Safari and iOS. I have added video like below mentioned code.
<video height=350 id='TestVideo' webkit-playsinline><source src='test.mp4' type=video/mp4></video>
On Chrome, IE, Firefox first frame of video coming as thumbnail image, but not coming on Safari and iOS.
simply add preload="metadata" in video tag and set #t=0.1 at url src, it will get the frame of 0.1s of your video as thumbnail
however, the disadvantage of this solution is when you click to play the video, it always start at 0.1s
<video preload="metadata" controls>
<source src="video.mp4#t=0.1" type="video/mp4">
</video>
If you want to do this without storing server side images it is possible, though a bit clunky... uses a canvas to record the first frame of the video and then overlay that over the video element. It may be possible to use the URL for the Canvas as a source for the Poster (eg video.poster = c.toDataURL();) but that requires correct CORS setup (not sure if the video was on your own server, and if you have control over that, so took the safest option). This will work best if video is correctly encoded for streaming (so MOOV atom is at the front of the video, otherwise it will be slow to draw the overlay - see this answer for more detail)
The HEAD contains styling for the video and the overlay (you will need to adjust sizing and position to suit your application)
<head>
<style>
video_box{
float:left;
}
#video_overlays {
position:absolute;
float:left;
width:640px;
min-height:264px;
background-color: #000000;
z-index:300000;
}
</style>
</head>
In the BODY you will need the div for the overlay and the video. The overlay div has an onclick handler to hide the overlay and start the video playing
<div id="video_box">
<div id="video_overlays" onclick="this.style.display='none';document.getElementById('video').play()"></div>
<video id="video" controls width="640" height="264">
<source src="BigBuck.mp4" type='video/mp4'>
</video>
</div>
</div>
Finally you will need code that will load the video, seek to the first frame and load the visual into a canvas that you then insert into the overlay
<script>
function generateOverlay() {
video.removeEventListener('seeked',generateOverlay); / tidy up the event handler so it doesn't redraw the overlay every time the user manually seeks the video
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
c.width = 640;
c.height = 264;
ctx.drawImage(video, 0, 0, 640, 264); // take the content of the video frame and place in canvas
overlay.appendChild(c); // insert canvas into the overlay div
}
// identify the video and the overlay
var video = document.getElementById("video");
var overlay = document.getElementById("video_overlays");
// add a handler that when the metadata for the video is loaded it then seeks to the first frame
video.addEventListener('loadeddata', function() {
this.currentTime = 0;
}, false);
// add a handler that when correctly seeked, it generated the overlay
video.addEventListener('seeked', function() {
// now video has seeked and current frames will show
// at the time as we expect
generateOverlay();
}, false);
// load the video, which will trigger the event handlers in turn
video.load();
</script>
this is a bit late but we had the same scenario. I can't use the attribute 'muted' because my videos are podcasts. This is what I came up with and I hope to share it with future visitors. What I did is load the video in the body tag, drew a canvas, retrieved as base64 and applied to the video as the background image.
Since my video should be fixed 150px in height, I computed the aspect ratio so that whatever height and width of the actual video, it will be resized into 150px height and dynamic width.
$('body').append('<video class="checkmeload" style="position:absolute;top:-10000px" controls preload="auto" playsinline src="//src-here"><source src="//src-here" type="//videotype-here"></video>');
$('body').find('.checkmeload').on('loadeddata', function(){
var video = $('.checkmeload');
var canvas = document.createElement('canvas');
aspectratio = (video[0].videoWidth / video[0].videoHeight);
newwidth = (150 * aspectratio);
canvas.width = newwidth;
canvas.height = 150;
var context = canvas.getContext('2d');
context.drawImage(video[0], 0, 0, canvas.width, canvas.height);
var dataURI = canvas.toDataURL('image/jpeg');
$('body').find('.checkmeload').remove();
$('#myvideo').css('background-image','url("'+dataURI +'")');
});
Source: How to set the thumbnail image on HTML5 video?
This worked for me:
<img src="thumbnail.png" alt="thumbnail" />
/* code for the video goes here */
Now using jQuery play the video and hide the image as
$("img").on("click", function() {
$(this).hide();
// play the video now..
})
Add #t=0.001 at the end of the video URL.
https://muffinman.io/blog/hack-for-ios-safari-to-display-html-video-thumbnail/

YouTube iframe api won't play from click handler on iOS

I am using the Youtube iframe api to show a custom thumbnail and play button over an embedded video. It is working everywhere (including android) except for iOS, where I get "If playback doesn't begin shortly, try restarting your device" behind the thumbnail. If I hide the thumbnail, I can play the video using Youtube's play button (before using my controls) and the html5 play button (after using my controls)
I am aware of the restriction on autoplaying videos, but this should get around that because it is triggered by a click handler, and works on android which has the same restriction
function loadVideo(videoID, title, description, thumbUrl, waitPlay) {
var playBtn = jQuery(".playerThumb");
jQuery(".playerTitle").text(title);
jQuery(".playerDesc").text(description);
jQuery(".playerEmbed").replaceWith("<div id='video' class='playerEmbed'></div>");
playBtn.css("background-image", "url(" + thumbUrl + ")").show().off('click').removeClass("ready");
jQuery("html, body").animate({ scrollTop: 0 }, 400, "swing", function(){});
ytPlayer = new YT.Player('video', {
videoId: videoID,
playerVars: {
rel: 0,
showinfo: 0,
autoplay: (waitPlay === true ? 0 : 1)
},
events: {
'onReady': onReady,
'onError': function(e){console.error(e);},
'onStateChange': function(e){if (e.data == YT.PlayerState.PLAYING) jQuery(".playerThumb").fadeOut();}
}
});
function onReady(e) {
playBtn.click(function() {ytPlayer.playVideo();}).addClass("ready");
if (waitPlay !== true) {
if (ytPlayer.getPlayerState() == YT.PlayerState.PLAYING) {
playBtn.hide();
}
}
}
}
How can I get this to work on iOS? Is my only option to just use the default play button for iOS?
Had the same issue and found the solution.
It turns out that on iOS you can't overlay the youtube video with any div, the user needs to click directly on the youtube iframe for the video to start.

Custom thumbnail or splash screen for embedded youtube video

Full Disclosure Confession: This is not a question, but a question with some answers.
I did not initially like the three choices of thumbnails that Youtube.com selected, so ...
Question: How do I display a custom thumbnail or splash screen for my embedded youtube video?
Answer #1: Accept Monetization option with Youtube.com and a button to create a custom thumbnail magically appears. NOTE: this was definitely NOT an acceptable option for me since my Youtube movie, entitled "My Love Song Forever", is a Love Song to my wife (whose lyrics I wrote and whose production I shared in). Have random ads appear together with my Love Song to my bride of over 51 years ... not a chance!!!
Answer #2: By pass such a requirement using css and frames:
var videoSrc = "http://www.youtube.com/embed/MxuIrIZbbu0";
var videoParms = "?autoplay=1&fs=1&hd=1&wmode=transparent";
// style of thumbNail's image must equal style of video for the 2 to overlap
var youtubeVideo = "" +
"<div>" +
"<iframe class='ls_video' src='" + videoSrc + videoParms + "'>" +
"</iframe>" +
"</div>";
var theThumbNail = "" +
"<div onclick=\"this.innerHTML = youtubeVideo;\">" +
"<img class='ls_video' src='images/MLSFthumbnail.jpg' style='cursor:pointer' alt='splash' \/> " +
"</div>";
document.write (theThumbNail);
I read somewhere that the thumbnail should spec at 1280px by 840px, so that is what I did.
IN THE INTEREST OF FULL DISCLOSURE, writing your own custom thumbnail THIS WAY will defeat the natural view counting that Youtube.com keeps track of. View counting will happen ONLY WHEN you go the monetization route.
THE CHOICE IS YOURS.
BOTTOM LINE ... I chose to be concerned about the View Count, so I regretfully chose one of the 3 thumbnail choices that Youtube.com offered;
See --- http://lovesongforever.com
Just copy and paste the code in an HTML file and enjoy the happy coding.
Using youtube api to manage the youtubed embedded video thumbnail.
<!DOCTYPE html>
<html>
<body>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
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: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event) {
$('#play_vid').click(function() {
event.target.playVideo();
});
}
$(document).ready(function() {
$('#player').hide();
$('#play_vid').click(function() {
$('#player').show();
$('#play_vid').hide();
});
});
</script>
<div id="player"></div>
<img id="play_vid" src="YOUR_IMAGE_PATH" />
</body>
</html>

Resources