It is easy to create a custom play button for an embed YouTube video using their API, however it seems that the button cannot launch the video in mobile environment, especially Android. When you click it there, screen simply goes forever black with ever spinning loading animation.
<div id="wrapper">
<div id="video">
</div>
Play
</div>
<script>
var player, tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('video', {
height: '320',
width: '240',
videoId: '5oxIQe3XngY',
playerVars: {
modestbranding: 1,
controls: 0,
rel: 0
}
});
player.addEventListener('onReady', function(e) {
document.getElementById('play').onclick = function() {
player.playVideo();
};
});
player.addEventListener('onStateChange', function(e) {
if (e.data == 1) {
document.getElementById('play').style.display = 'none';
}
});
};
</script>
Here's the fiddle: http://jsfiddle.net/HArsN/
Any solution to that? Is it necessary to launch the video through bundled button only?
Related
I have a HTML5 video element which is showing mp4 video in LoadingController(Ionic framework). My problem is that video is not immediately loaded after loader is shown, I can see the default thumbnail/poster of html5 video element for 0.2s and just after this is video shown. The problem occurs just on Android device, iOS devices are playing video instantly.
Loader initialization code:
var preloaderOptions: object ={
spinner: 'hide',
duration: 2500,
message: `
<div class="custom-spinner-container">
<div class="custom-spinner-box">
<video id="videoPlayer" autoplay muted loop playsinline webkit-playsinline preload="metadata">
<source src="./assets/videos/loader.mp4" type="video/mp4" />
</video>
<p>`+loaderMessages[Math.floor(Math.random()*loaderMessages.length)]+`</p>
</div>
</div>`,
cssClass: 'custom-loading'
};
this.preloaderController.create({...preloaderOptions}).then((preloader) => {
this.preloader = preloader;
preloader.present().then(el => {
let video = this.preloader.getElementsByTagName('video')[0];
video.autoplay= true;
video.playsInline = true;
video.muted = true;
video.loop = true;
video.preload="metadata";
video.webkitPlaysInline = true;
video.play();
});
});
I also tried to place poster image into video markup and typescript, but not helped to get rid of default thumbnail. Preload="auto" wasn't working too.
Thanks for help.
Ok, so I fixed it by adding white poster jpg picture, but the key is to show video just before calling play() method.
this.preloaderController.create({...preloaderOptions}).then((preloader) => {
this.preloader = preloader;
let video = this.preloader.getElementsByTagName('video')[0];
video.style.display = "none";
preloader.present().then(el => {
video.autoplay= true;
video.playsInline = true;
video.muted = true;
video.loop = true;
video.preload="auto";
video.poster = "./assets/images/loader_poster.jpg";
video.style.display = "inline-block";
video.webkitPlaysInline = true;
video.play();
});
});
I am using jquery to load YouTube Video through iframe to reduce the initial page load time. Using this approach – only the video thumbnail is loaded along with the page and the actual player loads when the user hits the play button. But AutoPlay is not working on Android and Iphones though it is perfectly working on desktops using windows. When I googled this problem, it turns out "Chrome and Safari browsers on iPhone and Android only allow playback of HTML5 video when initiated by a user interaction. They block embedded media from automatic playback to prevent unsolicited downloads over cellular networks." I want to autoplay the video. Please help.
Here is my jquery
document.addEventListener("DOMContentLoaded",
function() {
var div, n,
v = document.getElementsByClassName("youtube-player");
for (n = 0; n < v.length; n++) {
div = document.createElement("div");
div.setAttribute("data-id", v[n].dataset.id);
div.innerHTML = YouTubeThumb(v[n].dataset.id);
div.onclick = YouTubeIframe;
v[n].appendChild(div);
}
});
function YouTubeThumb(id) {
var thumb = '<img src="https://i.ytimg.com/vi/ID/mqdefault.jpg">',
play = '<div class="play"></div>';
return thumb.replace("ID", id) + play;
}
function YouTubeIframe() {
var iframe = document.createElement("iframe");
var embed = "https://www.youtube.com/embed/ID?autoplay=1";
iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
this.parentNode.replaceChild(iframe, this);
}
and the HTML
<div class="youtube-player" data-id="YouTube_Video_ID"></div>
try this example:-
// 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 (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();
}
I am trying to use the a YouTube iframe API with my cordova-android project. When I run the code in a browser on my computer it runs perfectly, but when i build my app and run it on my phone the page containing the iframe will not load, and i get the following error in my console:
XMLHttpRequest cannot load chrome-extension://boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js. Cross origin requests are only supported for HTTP
Here is my code:
<div class='ui-body ui-body-a'>
<!-- 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',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
console.log('Loaded Video)
}
// 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>
</div>
Thanks in advance!
I got it to work by using glitchbone's cordova plugin YoutubeVideoPlayer.
I am using the following code to play HTML5 videos
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script type="text/javascript" id="youtubeplayer">
</script>
<script>
document.getElementById('youtubeplayer').style.width=window.innerWidth;
document.getElementById('youtubeplayer').style.height=window.innerHeight;
// 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', {
//videoId: localStorage.getItem('videoid'),
videoId : "8UVNT4wvIGY",
width : Math.abs(window.innerWidth*0.99),
height : Math.abs(window.innerHeight*0.99),
allowFullScreen : true,
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>
Basically I am embedding it in a HTML5 page.
It works very well on Desktop, but on a Android device (Google Nexus 10), it just shows the title of the video and the video doesn't load.
Fitvids plugin worked super well for me and played nicely within the bootstrap framework I was using.
From their github page:
<script src="path/to/jquery.min.js"></script>
<script src="path/to/jquery.fitvids.js"></script>
<script>
$(document).ready(function(){
// Target your .container, .wrapper, .post, etc.
$("#thing-with-videos").fitVids();
});
</script>
Boom done!
I am trying to create an offline video player that would download video content from my site for later viewing offline via an HTML5 video element. The code below works fine in Chrome for the desktop, but not on mobile (Nexus S smartphone, Nexus 7 tablet, 4.1 since only that runs chrome, which is required for the filesystem api). I am using the filesystem API that is supported by chrome on both the desktop and mobile.
I have confirmed it is correctly storing the file on the mobile device and I can retrieve the file correctly, but for some reason after retrieving the video from the localsystem chrome does not want to play the video. This is true whether I am using the html5 video element or whether I am navigating directly to the filesystem URL. When I use the html5 video element it returns the error media_err_not_supported. I have confirmed that the device can play the video if I navigate directly to it on my server (without first storing it using the filesystem api), so the issue is not a codec or video format problem. I am also using the video/mp4 mime type in both cases.
Again, this works on desktop, but not mobile. Any ideas?
Here is the code we are using:
<!DOCTYPE html >
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
var _fs;
var filename = "test3.mp4";
var diskSpaceRequired = 10 * 1024 * 1024;
$(document).ready(function () {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
function onInitFs(fs) {
_fs = fs;
getVideo(fs);
}
if (!!window.requestFileSystem) {
window.webkitStorageInfo.requestQuota(
window.webkitStorageInfo.PERSISTENT,
diskSpaceRequired, // amount of bytes you need
function () { },
function () {}
);
window.requestFileSystem(window.PERSISTENT, diskSpaceRequired, onInitFs, function () { alert('error'); });
} else {
alert('not supported');
}
$("#play").on('click', playVideo);
$("#ourVideo").on('error', function(e) { console.log('ERROR!!!', e, arguments);
console.log($("#ourVideo")[0].error);
});
});
function playVideo() {
_fs.root.getFile(filename, {}, function (fileEntry) {
$("#ourVideo").attr('src', fileEntry.toURL());
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
$("#ourVideo").get(0).play();
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
function getVideo(fs) {
fs.root.getFile(filename, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fetchResource(fileWriter);
}, errorHandler);
}, errorHandler);
}
function errorHandler(e) {
console.log('error', e);
}
function fetchResource(fileWriter) {
console.log('fetchresource');
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("GET", "http://mydomain.com/trailer.mp4", true);
xhr.onload = function(e) {
if (this.status == 200) {
var bb = new WebKitBlobBuilder();
bb.append(this.response);
var blob = bb.getBlob("video\/mp4");
fileWriter.write(blob);
} else {
console.log(this.status);
}
};
xhr.send();
}
</script>
<title>foo</title>
</head>
<body>
<input type="button" value="Play Video" id="play"/>
<video id="ourVideo" controls="">
<source id="vidSource" type="video/mp4"/>
</video>
</body>
</html>
The problem looks like your android chrome coudn't access the android file system correctly, For that you can use nanoHttpd server for access android local files in device or sdcard.
for NanoHttpd server use this one class in your application and pass the media file location as http://localhost:8081/sdcard/(your_media_location).mp4
or get nanoHttpd from https://gist.github.com/1893396
I think this is more accurate to access sdcard files than directly calling for them
try change html part to
</head>
<body>
<input type="button" value="Play Video" id="play"/>
<video id="ourVideo" controls="">
<source src="video1.mp4" type= "video/mp4">
<source src="video1.ogv" type= "video/ogg">
</video>
</body>
you can convert your mp4 to ogv using
http://video.online-convert.com/convert-to-ogg
and put ogv file in the same location in mp4
**for more information check out these
http://www.broken-links.com/2010/07/08/making-html5-video-work-on-android-phones/
HTML5 <video> element on Android does not play