insert ads on HTML5 video - html

How can I insert ads on html5 video tag before the main video plays? Is there any open source tools to make this easier? Is there any reference that can guide me there?
It is working with this code:
<script type="text/javascript">
// listener function changes src
function myNewSrc() {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src="../main.webm";
myVideo.load();
myVideo.play();
}
// function adds listener function to ended event -->
function myAddListener(){
var myVideo = document.getElementsByTagName('video')[0];
myVideo.addEventListener('ended',myNewSrc,false);
}
</script>
but I can't when it play the second one. It shows the poster. How do I get rid of the poster?

This is a quick off the cuff start of a solution that should at least point you in the right direction. This gives you a singleton with an init method that when called sets up a preroll on a particular video element.
var adManager = function () {
var vid = document.getElementById("myVid"),
adSrc = "videos/epic_rap_battles_of_history_16_adolf_hitler_vs_darth_vader_2_1280x720.mp4",
src;
var adEnded = function () {
vid.removeEventListener("ended", adEnded, false);
vid.src = src;
vid.load();
vid.play();
};
return {
init: function () {
src = vid.src;
vid.src = adSrc;
vid.load();
vid.addEventListener("ended", adEnded, false);
}
};
}();
There are a number of things that aren't covered here, though. For instance, if you set the init method to be called when you start playing the video, you'll need to keep a flag that indicates whether there's an ad playing so that the play handler won't do anything when you're transitioning from the ad to the content (which requires a "play" event after the load() call in order to get the seamless playback).
We use something similar in our video playing project, and most of the video ad services out there do something like this for HTML based video playback (as opposed to Flash video playback).
It's relatively straightforward, but you just have to make sure to keep track of when event callbacks should be fired and when to add and remove those callbacks.
Another thing to consider is the unreliability of the "ended" event. I haven't yet figured out when and on which platforms it consistently fires, but it's a fairly well known problem. A possible solution is to use "timeupdate" instead and test whether the "currentTime" property is somewhere around a second less than the "duration" property so you know you're right at the end of the video.

Sorry I can't test this code right now but in theory this should work.
<script>
// you will want to do checking here to see if the browser supports the video element
document.getElementById('video').addEventListener('ended', function()
{
// the ad finished playing so update the src attribute to the real video
document.getElementById('video').src = 'mainvideo.webm';
});
</script>
<video id="video" src="ad.webm">
</video>

You may want to look at what Popcorn.js can do. It allows you to interact with Html5 video and overlay text and a lot of other cool things:
http://popcornjs.org/documentation

#natlee75 For me this didn't work
I changed It to this:
$( document ).ready(function() {
var adManager = function () {
var vid = document.getElementById("vid1564730217"),
adSrc = "http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_1mb.mp4",
src;
var adEnded = function () {
vid.removeEventListener("ended", adEnded, false);
vid.src = src;
vid.load();
vid.play();
};
return {
init: function () {
src = vid.src;
vid.src = adSrc;
vid.load();
vid.addEventListener("ended", adEnded, false);
}
};
}().init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="vid1564730217" src="http://techslides.com/demos/sample-videos/small.mp4" width="100%" style="max-height:600px;" poster="http://orperry.com/sample/wp-content/uploads/2015/12/sample-logo.png" controls>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

Have you ever watched a video online and seen a banner ad displayed on
top of the video? Or watched a video and seen an ad appear halfway
through? How about a rich media ad take over the screen when using a
mobile app?
This question was asked 8 years ago, Things have changed over the years and now we have protocols like VAST, VPAID, VMAP, and MRAID.
Read about them here.

Related

Remove black loading screen from YouTube embed looped video

I've checked out the other threads about this, but couldn't really find what I'm after.
I've embedded a YouTube video in iFrame form. It's set to autoloop. Here's the parameters:
?showinfo=0&rel=0&autoplay=1&loop=1&controls=0&playlist=SeFzUzde5BM
The problem is that before the video starts, there's a black screen with a loading bar. That in itself isn't too bad, but then when the video goes to loop, it does that again! Why does it need to load itself twice? Is there anyway to have it seamlessly loop, without the loading screen breaking up each loop?
Your question seems to be answered here:
YouTube embedded video auto loop without refresh screen
However if that link becomes un-available the answer is using a Youtube Embed Api code. called player.getPlayerState() .You basically check that the video has "ended" and then run the .playVideo(); function. which starts it again immediately.
Youtube API : focused on Playback Status
I added this 'if' statement to the code provided at the top of the Youtube API page.
if (event.data === YT.PlayerState.ENDED) {
player.playVideo();
}
NOTE: As you can see you have to set it up as a separate script first instead of running it in-line in the html (it's easier to keep track of too). I suggest looking at the YouTube API linked above for extra help.
Jimmy's solution looks good. I ended up using an HTML video player, but if anyone is curious, this is the solution that was working for me when I was using the iframe.
I had to know the time of the video (15s) and set it to loop .1s before that (14.9s). Otherwise, there'd be a little "blip" effect. I used an interval to constantly check the time. If there's a way to dynamically hook into the 0.1s spot before video end, I'd recommend that, but I couldn't find that. I also use a little fade effect so the transition is smoother.
<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: YOUR_ID_HERE,
playerVars: {
controls: 0,
showinfo:0,
rel:0,
},
events: {
'onReady': onPlayerReady,
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
var interval_is_stopped = false;
setInterval(function (){
var current_time = event.target.getCurrentTime();
if (current_time > 14.9 && !interval_is_stopped) {
interval_is_stopped = true;
jQuery('#player').fadeTo(400, 0.7, function(){
player.seekTo(0);
jQuery(this).fadeTo(400, 1, function(){
interval_is_stopped = false;
});
});
}
}, 10);
}
</script>

HTML5 video: click on play button, play another video

I need to change the video link on click on Play button and also need to auto play the video.
<video id="video" src="dhoni.mp4" width="320" height="240" controls>
</video>
<script>
$(document).ready(function () {
var video = document.getElementById('video');
video.onplay = function (e) {
$('video').attr({'src': 'ran.mp4'});
$('video')[0].play();
};
});
</script>
Exists many kinds of solution for what you want, I made an example how you do it
The simple way is just make two videos the first become hidden when the second is playing.
The other way is like the first but you use a image to represent the video1 when the user click in the image, so the video2 start, and you hide the image when the user click.
The others solutions like you're trying is more complicated because if you try to replace the src atribute of a video by other src exist a problem to load this, this involve ajax blob request and this will cause much issues to handle, for example when I trying to load a video that's not hosted in my server, and other things like the how the way firefox, chrome and other browsers render the video.
https://jsfiddle.net/5mek5ffd/27/
HTML
<video id="video1" src="http://techslides.com/demos/sample-videos/small.mp4" width="320" height="240" controls>
</video>
<video id="video2" class="hidden" src="https://static.videezy.com/system/resources/previews/000/004/147/original/jelly-fish.mp4" width="320" height="240" controls="">
</video>
CSS
.hidden{ display:none }
JS
function changeVideo(video1, video2){
try {
// pause the video
jQuery(video1)[0].pause();
// set the seconds to 0
jQuery(video1)[0].currentTime = 0;
// add the hidden class to the video1
jQuery(video1).addClass("hidden");
// remove the hidden class to the video2
jQuery(video2).removeClass("hidden");
// pause the video2 - it's necessary cause the video was ended
jQuery(video2)[0].pause();
// set the seconds to 0 to the video 2
jQuery(video2)[0].currentTime = 0;
} catch(e){
// if something goes wrong put the message on console
//prevent the script stop the other scripts too
console.log(e.message);
return false;
}
}
jQuery(document).ready(function($){
try {
// if exists the video1 put it on video1 variable
// if exists the video2 put it on video2 variable
var $video1 = $('#video1').length > 0 ? jQuery('#video1') : false,
$video2 = $('#video2').length > 0 ? jQuery('#video2') : false;
// if exists the video1 and video 2
if($video1 && $video2){
// if the #video1 is starting to play
$video1.on("play", function() {
console.log($video2[0].duration);
// call change video function
changeVideo("#video1","#video2");
// the [0] represents the javascript dom object
// if the seconds is 0 in my video 2 then play it
if($video2[0].currentTime == 0 )
$video2[0].play();
});
// start the video1 if the page is ready added 1 sec for delay,
// to not cause the impress wrong of the video
setTimeout(function() {
if($video2[0].currentTime == 0)
$video1[0].play();
},1000);
// if the video was ended return to the first video
$video2.on("ended", function(){
changeVideo("#video2","#video1");
});
}
} catch(e){
// if something goes wrong put the message on console
//prevent the script stop the other scripts too
console.log(e.message);
}});

Detect HTML Video Source Change Event (addEventListener)

I'm trying to find an event for when an HTML video changes it's source. I'm using mediaelement.js as my skin but I couldn't find any extra events that it had.
All of my searches just turns up instructions on how to change the source, not detect if the source was changed.
I'm hoping I can just do something like
.addEventListener('sourceChange', function (e) { })
but I can't seem to find if there's an actual event.
Thanks!
You can use loadedmetadata, loadeddata as well as canplay events to find out if a source has loaded and can be played. The event contains reference to the source video element in question and from there you can check if the url has changed compared to the previous one.
Example (proof of concept)
var cUrl = v.src; // current url
v.onloadedmetadata = function() {
if (this.src !== cUrl) {
i.innerHTML = "<b>Source changed!</b>";
cUrl = this.src; // update, etc..
}
else {
i.innerHTML = "Source is playing... (changes source in 5 sec.)";
setTimeout(function() {
i.innerHTML = "Loading new source...";
v.src = "http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_30mb.mp4";
}, 5000);
}
};
<div id=i>Loading video, please wait...</div><br>
<video id=v autoplay muted controls
src="http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_50mb.mp4"></video>
Can you not use "loadeddata" event as specified here http://www.mediaelementjs.com/#api

Autoplay HTML5 video after it loads

I want to autoplay an HTML5 video only after it loads. I would also like to have a progress bar (GIF or CSS) while it loads. Any help?
Not sure whether or not you want it to play only after the page loads, or after the video itself has finished buffering.
If you want it to play automatically upon the page loading you would want to use the tag's "autoplay" attribute.
Example
<video controls autoplay> </video>
For easy to understand information on how to make some rather cool looking loading bars in CCS3, see here. CSS-tricks always has some interesting stuff.
UPDATE 2 Hey so this answer is a specific work around for this scenario (only a 12sec. video for a slow connection wanting to be played back smoothly) nonetheless this should fill your needs:
$(document).ready(function() {
_V_("example_video_1").ready(function(){
var myPlayer = this;
myPlayer.on("progress", out_started);
});
});
function out_started(){
myPlayer =this;
var myTextArea = document.getElementById('buffered');
bufferedTimeRange=myPlayer.buffered();
if ( (bufferedTimeRange.start(0)==0 ) && ( bufferedTimeRange.end(0) - bufferedTimeRange.start(0) > 10 ) ){
myPlayer.play();
}
}
So some things, bufferedTimeRange can be more then one single rnge of time (but with only 12 sec. of video odds are only one as docs say only 1 ussualy ) .. but not guaranteed . None the less here's a link demoing it http://ec2-23-20-36-210.compute-1.amazonaws.com/video-js.html Hopeully this helps! also if 10 second of buffered video is not enough you can change the 10 to a 12 in the if statement
Original Answer
I am not sure why you would want to do this ... but video.js does make it possible
if you have a video element called example_video_1 you can write a javscript that look's like this (not this is if you choose to use video.js which again I recomend set up is easy see http://www.videojs.com/ for an example and get started to actually set it up)
VideoJS("example_video_1").ready(function(){
var myPlayer = this;
var howMuchIsDownloaded = myPlayer.bufferedPercent();
if(howMuchIsDownloaded == 1){
myPlayer.play(); //start playing the video
}else{
setTimeout(arguments.callee, 100);
}
});
Update it appears the API call layed out above is presently broken for Video.js (bug has been reported) Here is an example to tell when a video has finished being buffered if your video tag id is "example_video_1"
$(document).ready(function() {
_V_("example_video_1").ready(function(){
var myPlayer = this;
myPlayer.on("loadedalldata", Done_download);
});
});
function Done_download(){
myPlayer =this;
var myTextArea = document.getElementById('buffered');
alert("The video has been fully buffered ");
myPlayer.off("loadedalldata", Done_download);
}
Note there seem's to be an internal mechanism in Video.js that will not allow an entire video stream to be buffered before playback has reached with a certain range of the video (at least with an .mp4 source)
#DONSA you can check out this strange behavior here video-js sample page ... ill keep it up for a couple day's on my test server
I have a cleaner example, also using video.js:
function progress(){
video = this;
if (video.bufferedPercent() > .95 && video.paused()) {
video.play();
}
}
$(document).ready(function() {
_V_("video").ready(function(){
this.on("progress", progress);
});
});
and
<video src="mcd.mp4" id="video">

Wait until an HTML5 video loads

I have a video tag, that I dynamically change its source as I am letting the user to choose from a number of videos from the database. The problem is that when I change the src attribute the video doesn't load even if I tell it to.
Here is my code:
$("#video").attr('src', 'my_video_'+value+'.ogg');
$("#video").load();
while($("#video").readyState !== 4) {
console.log("Video is not ready");
};
The code still stays in a infinite loop.
Any help?
EDIT:
To Ian Devlin:
//add an listener on loaded metadata
v.addEventListener('loadeddata', function() {
console.log("Loaded the video's data!");
console.log("Video Source: "+ $('#video').attr('src'));
console.log("Video Duration: "+ $('#video').duration);
}, false);
Ok this is the code I have now. The source prints great, but I still can't get the duration :/
You don't really need jQuery for this as there is a Media API that provides you with all you need.
var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();
The Media API also contains a load() method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."
(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType() function to decide on which one to play).
You can then wait for either the loadedmetadata or loadeddata (depending on what you want) events to fire:
video.addEventListener('loadeddata', function() {
// Video is loaded and can be played
}, false);
In response to the final part of your question, which is still unanswered... When you write $('#video').duration, you're asking for the duration property of the jQuery collection object, which doesn't exist. The native DOM video element does have the duration. You can get that in a few ways.
Here's one:
// get the native element directly
document.getElementById('video').duration
Here's another:
// get it out of the jQuery object
$('#video').get(0).duration
And another:
// use the event object
v.bind('loadeddata', function(e) {
console.log(e.target.duration);
});
you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.
<video preload="none">
call function on load:
<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">
get video duration
var video = document.getElementById("video");
var duration = video.duration;