HTML5 Video - How to do a seamless play and/or loop of several videos? - javascript

How can I reliably play several videos one after another seamlessly? As there is a small pause or flicker between playing 2 videos.
In my particular example I have 3 videos. I need to play all 3 of them seamlessly one after another, and I also need to loop middle video an arbitrary number of times (say 2 or 3). All of that needs to happen seamlessly and consistently across different browsers.
I've been trying everything under the moon, from starting video playback on video end, to using several video tags and hiding and replacing them, I even tried to implement this in Flash, but alas nothing works, and the same problem happens in current Flash as well.
I've seen this (or similar) question asked many times but I haven't seen a reliable solution yet.
Does anyone know a solution to this?

After trying various things I have finally been able to create what seems to be a working solution. I haven't tested this on older browsers or other OSes, but this works on latest versions of Chrome, IE, Firefox and Opera. (Although some more feedback of whether this works on other systems would be appreciated)
The idea is to have all 3 videos output frames to HTML5 canvas. The original videos are hidden and preloaded in advance to avoid pause between loading.
Here is the code:
var playCounter = 0;
var clipArray = [];
var $video1 = $("#video1");
var $video2 = $("#video2");
var $video3 = $("#video3");
$video1.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4");
$video2.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4");
$video3.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4");
var timerID;
var $canvas = $("#myCanvas");
var ctx = $canvas[0].getContext("2d");
function stopTimer() {
window.clearInterval(timerID);
}
$('#startPlayback').click(function() {
stopTimer();
playCounter = $('#playbackNum').val();
clipArray = [];
// addd element to the end of the array
clipArray.push(1);
for (var i = 0; i < playCounter; i++) {
clipArray.push(2);
}
clipArray.push(3);
$video2[0].load();
$video3[0].load();
$video1[0].play();
});
function drawImage(video) {
//last 2 params are video width and height
ctx.drawImage(video, 0, 0, 640, 360);
}
// copy the 1st video frame to canvas as soon as it is loaded
$video1.one("loadeddata", function() {
drawImage($video1[0]);
});
// copy video frame to canvas every 30 milliseconds
$video1.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video1[0]);
}, 30);
});
$video2.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video2[0]);
}, 30);
});
$video3.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video3[0]);
}, 30);
});
function onVideoEnd() {
//stop copying frames to canvas for the current video element
stopTimer();
// remove 1st element of the array
clipArray.shift();
//IE fix
if (!this.paused) this.pause();
if (clipArray.length > 0) {
if (clipArray[0] === 1) {
$video1[0].play();
}
if (clipArray[0] === 2) {
$video2[0].play();
}
if (clipArray[0] === 3) {
$video3[0].play();
}
} else {
// in case of last video, make sure to load 1st video so that it would start from the 1st frame
$video1[0].load();
}
}
$video1.on("ended", onVideoEnd);
$video2.on("ended", onVideoEnd);
$video3.on("ended", onVideoEnd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="border">
<video id="video1" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<video id="video2" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<video id="video3" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<div>
<canvas id="myCanvas" width="640" height="360"> </canvas>
</div>
<div role="controls">
<div>
<label>
Times the middle video will repeat itself:
</label>
</div>
<div>
<input id="playbackNum" value="1" />
</div>
<p>
<button id="startPlayback">Start</button>
</p>
</div>
</div>
Please note, the code is not very pretty and would benefit from some cleanup and optimization, but at least this should show the way to work around the problem and implement a seamless playback of several videos in HTML5.
Also make sure to include jQuery source file in html file location for the code to work.

I have used VideoJS for some time and it allows seamless video playing.
http://videojs.com
You will be required jQuery for this. There are many other jQuery video players.

Related

check when video starts playing after populating src

I use the following code to check if the user is on desktop or mobile, if on desktop the src="" attribute of the video sources is populated. All fine. After populating the src attribute, I want to check the video has loaded before displaying it. Is there a way to do this?
Thanks!
JS
//video
if($.browser.mobile)
{
console.log("is mobile")
// it is mobile browser
}
else
{
console.log("is desktop")
// no mobile browser
var sources = document.querySelectorAll('video#patient-video source');
// Define the video object this source is contained inside
var video = document.querySelector('video#patient-video');
for(var i = 0; i<sources.length;i++) {
sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
}
// If for some reason we do want to load the video after, for desktop as opposed to mobile (I'd imagine), use videojs API to load
video.load();
video.muted= "muted";
$(".main-area--cris-pro").addClass("loaded")
}
To check if it's a mobile browser, I use the plugin:
detectmobilebrowser.js
My HTML is as follows:
<video id="patient-video" width="100%" preload="none" poster="../../assets/img/patient-home-1600.jpg" autoplay loop>
<source data-src="../../assets/video/patient-home-video-comp.mp4" src="" type="video/mp4">
<source data-src="../../assets/video/patient-home-video-comp.webm" src="" type="video/webm">
<source data-src="../../assets/video/patient-home-video-comp.ogv" src="" type="video/ogg">
</video>
Use canplaythrough event.
The canplaythrough event is fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
var sources = document.querySelectorAll('video#patient-video source');
var video = document.querySelector('video#patient-video');
for (var i = 0; i < sources.length; i++) {
sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
}
video.muted = true;//Set boolean value
video.addEventListener('canplaythrough', function() {
alert('Video Loaded!');
video.muted = false;
$(".main-area--cris-pro").addClass("loaded");
});

Can't get HTML5 video to loop back to first frame.

I would like for an HTML5 video of mine to loop back to the first frame and pause after playback.
I found this page here and am using the code near the bottom of the page by "Offbeatmammal" which is:
<div id="vOverlay" style="position:relative; width:600px; height:300px; z-index:2;"></div>
<video style="position:relative; top:-300px; z-index:1;width:600px;height:340px;" width="600" height="409" id=videoPlayer controls="controls">
<source src="video.mp4" type="video/mp4">
</video>
<script>
var v = document.getElementById('videoPlayer');
var vv = document.getElementById('vOverlay');
<!-- Play, Pause -->
vv.addEventListener('click',function(e){
if (!v.paused) {
console.log("pause playback");
v.pause();
v.firstChild.nodeValue = 'Pause';
} else {
console.log("start playback")
v.play();
v.firstChild.nodeValue = 'Play';
}
});
</script>
I have found a few threads that seem to indicate i need to use this.currentTime = 0; but I have no clue where to add this to the code above. I tried several different places and it just isn't working. Any help is much appreciated.
Thanks!
When the video is finished. WHEN is key here. You need to search for the "playback finish" event.
seach google for "html5 video events" and you'll find this:
http://www.w3schools.com/tags/ref_av_dom.asp
then the code you need to write is:
v.addEventListener("ended", function(){
this.currentTime = 0;
});

Prevent reset of currentTime when video loads?

I want to be able to reload the video into the HTML5 video without having to reset the currentTime when it is loaded. The way I am currently doing it is the following:
<button onclick="getCurTime()" type="button">Get current time position</button>
<button onclick="setCurTime()" type="button">Set time position to 5 seconds</button><br>
<div style="width:800px; height:445px;">
<video id="myVideo" width="100%" height="100%" controls="controls">
<source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" type="video/mp4">
</video>
<script>
var vid = document.getElementById("myVideo");
function setCurTime() {
vid.currentTime=100;
}
$(document).ready(function ()
{
$('#myVideo').videocontrols(
{
preview:
{
sprites: ['big_bunny_108p_preview.jpg'],
step: 10,
width: 200
},
theme:
{
progressbar: 'blue',
range: 'pink',
volume: 'pink'
}
});
vid.play();
});
setInterval(function(){
if(vid.currentTime > vid.duration-1)
{
myVideo.src = "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";
myVideo.load();
myVideo.play();
vid.currentTime = vid.duration-60*5
}
}, 1);
</script>
</div>
How would I go about doing this? Is there even a way to just update the data in the video player without having to reload the video? I want to be able to do this so if someone makes a modification to the video, it will just update the data in the video player so the user doesn't have to reload the whole video again.
per discussion in comment thread above, I'm still not 100% sure why you're reloading the same video so I may be missing some context, but the following code will let you change the video source but preserve the current time. It does assume jQuery for the event handler (though you can easily use the regular javascript event handler on the same event to do the same thing)
<video id="v" width="320" height="240" controls="controls" mute>
<source src="Video.mp4" />
</video>
<button onclick="reload()">Reload</button>
<script>
function reload() {
vid=document.getElementById("v")
// record the current time for the video that is playing
curTime = vid.currentTime
// set the source for the replacement video...
vid.src = "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";
// ... and load it
vid.load();
// add event handler for "canplay" to set the time, and then start the video
$("#v").on("canplay",function() {
vid.currentTime = curTime
vid.play();
// remove the event to stop it triggering multiple times
$("#v").off("canplay")
})
}
</script>

How to take youtube screenshot

<script src="jquery.js"></script>
<video id="video" controls preload="none" width="640" poster="http://media.w3.org/2010/05/sintel/poster.png" onloadedmetadata="$(this).trigger('video_really_ready')">
<source id='mp4' src="http://media.w3.org/2010/05/sintel/trailer.mp4" type='video/mp4' />
<source id='webm' src="http://media.w3.org/2010/05/sintel/trailer.webm" type='video/webm'/>
<source id='ogv' src="http://media.w3.org/2010/05/sintel/trailer.ogv" type='video/ogg' />
</video>
<br />
<input type="button" id="capture" value="Capture" /> Press play, and then start capturing
<div id="screen"></div>
<script>
var VideoSnapper = {
/**
* Capture screen as canvas
* #param {HTMLElement} video element
* #param {Object} options = width of screen, height of screen, time to seek
* #param {Function} handle function with canvas element in param
*/
captureAsCanvas: function(video, options, handle) {
// Create canvas and call handle function
var callback = function() {
// Create canvas
var canvas = $('<canvas />').attr({
width: options.width,
height: options.height
})[0];
// Get context and draw screen on it
canvas.getContext('2d').drawImage(video, 0, 0, options.width, options.height);
// Seek video back if we have previous position
if (prevPos) {
// Unbind seeked event - against loop
$(video).unbind('seeked');
// Seek video to previous position
video.currentTime = prevPos;
}
// Call handle function (because of event)
handle.call(this, canvas);
}
// If we have time in options
if (options.time && !isNaN(parseInt(options.time))) {
// Save previous (current) video position
var prevPos = video.currentTime;
// Seek to any other time
video.currentTime = options.time;
// Wait for seeked event
$(video).bind('seeked', callback);
return;
}
// Otherwise callback with video context - just for compatibility with calling in the seeked event
return callback.apply(video);
}
};
$(function() {
$('video').bind('video_really_ready', function() {
var video = this;
$('input').click(function() {
var canvases = $('canvas');
VideoSnapper.captureAsCanvas(video, { width: 160, height: 68, time: 40 }, function(canvas) {
$('#screen').append(canvas);
if (canvases.length == 4)
canvases.eq(0).remove();
})
});
});
});
</script>
How can I add youtube video instead. Could not play youtube video in video tag. embed tag is working to play youtube video. How to take screenshot by placing youtube video inside embed tag. Please help me
I could solve this with ffmpeg.
Just run
ffmpeg -i inputfile.avi -r 1 -t 1 -ss 00:00:03 image-%d.jpeg
where
-i inputfile.avi - input file
-r 1 - one frame per second
-t 1 - how many seconds should be converted to images
-ss 00:00:03 - from what second to start
image-%d.jpeg - resulting filename template
Found here http://linuxers.org/tutorial/how-extract-images-video-using-ffmpeg
The following bookmarklet capture a Youtube video at click time, in the current video resolution and quality, as you are seeing it, but without the toolbars overlays.
javascript:void(function(){let canvas=document.createElement("canvas"),video=document.querySelector("video"),ctx=canvas.getContext("2d");canvas.width=parseInt(video.offsetWidth),canvas.height=parseInt(video.offsetHeight),ctx.drawImage(video,0,0,canvas.width,canvas.height);var base64ImageData=canvas.toDataURL("image/jpeg"),o = new Date(0),p = new Date(video.currentTime*1000),filename="📷Capture_"+new URL(document.location.href).searchParams.get("v")+"_"+document.title+"#"+new Date(p.getTime()-o.getTime()).toISOString().split("T")[1].split("Z")[0]+".jpg",a=document.createElement("a");a.download=filename,a.href=base64ImageData,a.click()}());
Enhancement of the bookmarklet found here https://github.com/ReeganExE/youtube-screenshot.:
Image served as file download.
Does not block the playing video.
The image title contains the Youtube ID, the video title, and the exact time of the capture in the video.
Modified to work also in Firefox
If manually set up image this might be help you.
Try add poster="placeholder.png" //photo you want to the video tag.
example
<video width="470" height="255" poster="placeholder.png" controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
<source src="video.webm" type="video/webm">
<object data="video.mp4" width="470" height="255">
<embed src="video.swf" width="470" height="255">
</object>
</video>

Display video duration from videoJS

I am working on an HTML5 video player with jQuery. For now I have my video player working very well but I want to get the variable for the video duration and show/display it in pure HTML page.
So from here you can take more info about this Jquery video player:
http://www.videojs.com/docs/api/
I think the variable for video duration is: myPlayer.duration();
How I can display this value in HTML?
Here is my HTML code to display the player:
<video id="vemvo-player" class="video-js vjs-default-skin" controls autoplay="true" width="950" height="534"
data-setup="{}">
<source src="[var.base_url]/uploads/[var.video_play]" type='video/flv' />
</video>
This is what I have tried to display this variable but it says that it is = "0" when on the video player it says that it's 4min:
<video id="vemvo-player" class="video-js vjs-default-skin" controls autoplay="true" width="950" height="534"
data-setup="{}">
<source src="[var.base_url]/uploads/[var.video_play]" type='video/flv' />
</video>
<div id="duration"></div>
<script type="text/javascript">
_V_("vemvo-player").ready(function(){
var myPlayer = this;
var howLongIsThis = myPlayer.duration();
$('#duration').html('Duration: ' + howLongIsThis);
});
</script>
Where is my mistake?
You can try this. It works for me.
var myPlayer = videojs('vemvo-player');
if (myPlayer.readyState() < 1) {
// wait for loadedmetdata event
myPlayer.one("loadedmetadata", onLoadedMetadata);
}
else {
// metadata already loaded
onLoadedMetadata();
}
function onLoadedMetadata() {
alert(myPlayer.duration());
$('#duration').html("Duration: " + myPlayer.duration());
}
var player = videojs('my-video', {
fluid:false, // videojs settings
controls:true,
height: '300'
});
$(document).ready(function(){
console.log(player.duration());
// will return video duration. Can't be used while page is loading.
console.log(player.currentTime());
// will return current time if video paused at some time. Intially it would be 0.
});
Those who might come here and are using videojs with Vue 3, also might work with similar frameworks like React.
Referring to this code and component usage - https://docs.videojs.com/tutorial-vue.html you can do the following changes to get the duration, height, and width.
// New Code here
this.player = videojs(
this.$refs.videoPlayer,
this.options,
function onPlayerReady() {
console.log("onPlayerReady", this);
}
);
this.player.one("loadedmetadata", () => {
var duration = this.player.duration();
console.log(`Duration of Video ${duration}`);
console.log(`Original Width of Video ${this.player.videoWidth()}`);
});
I was having troubles to get the real duration of videos (using videojs v7.18.*) resulting in bugged custom progressbar! The problem was that player.duration() always returns rounded number while player.liveTracker.seekableEnd() returns the real value but only after start event.
For example, if real duration is 13.456s, these values are returned for videojs player object p:
| On ready | On load | On start
----------------------------|-------------|---------|----------
p.duration() | 0 | 14 | 14
p.liveTracker.seekableEnd() | 14 | 14 | 13.456
I've ended up with this solution in React:
const onDurationChange = () => {
const dur = player?.liveTracker.seekableEnd() || player?.duration() || 0;
setDurationInSec(dur);
}
return <video ref={videoRef} onDurationChange={onDurationChange}>
As you're using jQuery, that can be done much easier :) You can use $.html to edit the html contents of a dom element. Your code will look something like this:
<div id="duration"></div>
<script type="text/javascript">
_V_("vemvo-player").ready(function(){
var myPlayer = this;
var howLongIsThis = myPlayer.duration();
$('#duration').html('Duration: ' + howLongIsThis);
});
</script>

Categories

Resources