I'm trying to play an 8.6 second video once completely, and then loop a small section of the video infinitely, to keep the illusion of a never-ending video. So far I've looked into the media fragments URI, and the ended event of the video. Setting the currentTime attribute in the ended event listener works, but it makes the video "blink".
At present, I'm using a timeupdate event listener to change the time when the video is approaching the end [shown below]
elem.addEventListener('timeupdate', function () {
if (elem.currentTime >= 8.5) {
elem.currentTime = 5;
elem.play();
}
}, false);
JSFiddle here
This works as well, but the video pauses visibly before restarting at 5 seconds. Is there a smoother way of playing the video once and then looping a segment of it?
Your code is fine, the problem is with your MP4 file! Try using a much smaller video like this one ( http://www.w3schools.com/tags/movie.mp4 ) to confirm the issue is not with your code.
So how can you achieve the same result but with large videos files?
You will need two video files:
video1 is the main video
video2 is the looping video
Remember: HTML5 video has no problem playing and looping large video files so we will use this method to play the videos.
In the example below we will play the first video and when it finishes we will execute a function to hide video1 and then show/play video2. (Video 2 is already set to loop)
Don't forget to load JQuery in your head otherwise this will not work.
<video id="video1" width="1080" height="568" poster="movie.png" autoplay onended="run()">
<source src="movie.webm" type="video/webm">
<source src="movie.ogg" type="video/ogg">
<source src="movie.mp4" type="video/mp4">
<object data="movie.mp4" width="1080" height="568">
<embed width="1080" height="568" src="movie.swf">
</object>
Optional test to be displayed if the browser doesn't support the video tag (HTML 5)
</video>
<video id="video2" width="1080" height="568" poster="loop.png" loop>
<source src="loop.webm" type="video/webm">
<source src="loop.ogg" type="video/ogg">
<source src="loop.mp4" type="video/mp4">
<object data="loop.mp4" width="1080" height="568">
<embed width="1080" height="568" src="loop.swf">
</object>
Optional test to be displayed if the browser doesn't support the video tag (HTML 5)
</video>
<script>
$( "#video2" ).hide();
function run(){
$( "#video1" ).hide();
$( "#video2" ).show();
document.getElementById("video2").play();
};
</script>
Try the following, to 'rewind' it as soon as it ends:
vidElem.addEventListener("ended", function () {
vidElem.currentTime = 2.5;
vidElem.play();
}, false);
Updated fiddle: http://jsfiddle.net/Lt4n7/1/
I just had to deal with the same problem and noticed the same issues with flickering. Here was my solution:
Get 2 videos (or sets of videos) - one for the non-looped section, the other for the looped section
Create 2 video elements
set the looping element to 'display:none'
Then just capture the ended event and swap display status (example uses jquery but you could use 'style.display="none/block"' just as easily:
VideoPlayer1 = document.getElementById('video1');
VideoPlayer2 = document.getElementById('video2');
VideoPlayer1.addEventListener('ended', videoLooper, false);
function videoLooper()
{
VideoPlayer2.play();
$(VideoPlayer2).show();
$(VideoPlayer1).hide();
}
You can't solve this issue in javascript. That delay you see depends on the video compression and the hardware.
To start playing at a time that is not 0, the video decoder has to go back and find a key frame and then build the current frame by reading everything between the last key frame and your chosen time.
I'm not an expert in video compression, but maybe there is a way to pick these key frames and place them exactly where you need them. I don't think it will be easy and smooth, though.
If you're looking for an easier solution, use #Random's, but it uses two <video> tags to work around this limit.
var iterations = 1;
var flag = false;
document.getElementById('iteration').innerText = iterations;
var myVideo = document.getElementById('video-background');
myVideo.addEventListener('ended', function() {
alert('end');
if (iterations < 2) {
this.currentTime = 0;
this.play();
iterations++;
document.getElementById('iteration').innerText = iterations;
} else {
flag = true;
this.play();
}
}, false);
myVideo.addEventListener('timeupdate', function() {
if (flag == true) {
console.log(this.currentTime);
if (this.currentTime > 5.5) {
console.log(this.currentTime);
this.pause();
}
}
}, false);
<div>Iteration: <span id="iteration"></span></div>
<video id="video-background" autoplay="" muted="" controls>
<source src="https://res.cloudinary.com/video/upload/ac_none,q_60/bgvid.mp4" type="video/mp4">
</video>
<div>Iteration: <span id="iteration"></span></div>
// Please note that loop attribute should not be there in video element in order for the 'ended' event to work in ie and firefox
Related
I got a project that has a video that plays in a loop. Here is the html for the video tag:
<video playsinline autoplay muted loop id="myVid">
<source src="River.mp4" type="video/mp4">
</video>
I would like the video to pause after a delay, and I am trying to implement this using javascript. My javascript code:
function stopVideo() {
var vid = document.getElementById('myVid');
vid.pause();
}
setTimeout(stopVideo, 900);
This is not working. Any ideas why? Thank you.
---------------------------------------------------------------EDIT--------------------------------------------------------------
if it helps, the error console is giving me a message:
TypeError: null is not an object (evaluating 'vid.pause')
Update based on new information from OP:
The null means the element is not found by getElementById(), indicating that the script is running before the DOM is built (ie. in the head tag).
Simply run the script code like this if in head:
window.onload = function() {
// code goes here
};
Or more the script tag to the bottom of the document before body close tag.
Old answer -
Before setting the timeout, make sure the video is actually playing. With a short delay of 900ms (0.9s) you can risk the timeout code triggers before the video has started playing.
To be sure the video is actually playing you can use events such as playing and timeupdate, but in timeupdate is likely not accurate for this scenario, so one way around is to only trigger when playing:
var vid = document.getElementById('myVid');
var reqId; // optional, prevents running more than one time
vid.addEventListener("playing", function() {
if (!reqId) reqId = setTimeout(stopVideo.bind(this), 2000);
});
function stopVideo() {
this.pause();
}
video {height:200px}
<video playsinline autoplay muted loop id="myVid">
<source src="//media.w3.org/2010/05/sintel/trailer.mp4" type="video/mp4">
</video>
It's working fine !
function stopVideo() {
var vid = document.getElementById('myVid');
vid.pause();
}
setTimeout(stopVideo, 5000);
<video playsinline autoplay muted loop id="myVid" width="400px" >
<source src="http://mazwai.com/system/posts/videos/000/000/123/original/victor_ciurus--5d_mark_iii_magic_lantern_14_bits_raw_video.mp4" type="video/mp4">
</video>
maybe, just increase the timer.
I would try something like this:
setTimeout(function () {stopVideo()}, 900);
I'm searching for a way to play html5 video after its fully loaded. And while video is still loading - showing video placeholder image.
Before i've used setTimeout function, but its not the way to accomplish this.
setTimeout(function() {
$('banner__video--fallback').fadeOut();
$('.banner__video')[0].play();
}, 800);
So what is the way around this to play video after its loaded?
EDITED:
With solution 'canplaythrough' video still start ot be playing before its fully loaded.
$('.banner__video')[0].addEventListener("canplaythrough", function () {
$('banner__video--fallback').fadeOut();
$('.banner__video')[0].play();
}, false);
Why don't you just use HTML5 video attributes? There's no need for javascript.
<video autoplay poster="/placeholder.jpg">
<source src="video.webm" type="video/webm">
<source src="video.mp4" type="video/mp4">
</video>
autoplay plays the video as soon as it is loaded and poster assigns an image to stand in the video while it's loading.
You should read more here: http://www.w3schools.com/html/html5_video.asp
I think this is a better option to play a video after its load:
var vid = document.getElementById("myVideo");
vid.oncanplaythrough = function() {
alert("Can play through video without stopping");
};
You can download video with ajax call like this:
Another: Force Chrome to fully buffer mp4 video or just use canplaythrough property.
Is there a better way / practice to get the same results as my example, and possibly avoid that 1 second lag when play(); is fired.
I don't need the entire video to loop, but to restart at a specific point in the video's timeline.
example: http://jsfiddle.net/8dsco0o3/
Repeat video to a specific time:
HTML:
<video id="myVideo" width="720" height="476" autoplay>
<source src="video.mp4" type="video/mp4">
</video>
JavaScript:
var vid = document.getElementById("myVideo");
vid.onended = function() {
vid.currentTime = 3;
vid.play();
};
I am struggling to get an HTML5 video to play when arriving at the page via an AJAX request.
If you refresh the page, or land directly on the page, it works fine. But when navigating to the page via AJAX it does not play.
The code is:
<video id="video" autoplay="autoplay" loop="loop" muted="muted" poster="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.jpg">
<source src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.mp4" type="video/mp4">
<source src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.webmhd.webm" type="video/webm">
<img src="http://localhost/wp-content/themes/studioindigo/videos/contactbackground.jpg" alt="your browser does not support html5 video">
</video>
I have tried firing the following code on success of AJAX page load:
video = document.getElementById('video');
video.load();
video.addEventListener('loadeddata', function() {
video.play();
}, false);
And also simply:
video = document.getElementById('video');
video.play();
I have also tried using plugins such as video.js, but to no avail.
I can't help but think I am missing something really simple. Surely if the video is on the page and has autoplay set, then it should just play regardless of whether you arrive at the page via AJAX or directly?
The AJAX request for the page only updates the #main element (which the video is inside) and the does history.pushState - could that be anything to do with it? It doesn't seem likely...
For anyone struggling with the same issue, I found that after the ajax call the video had the property 'paused: true' even thought autoplay was set and I was calling video.play() on 'loadeddata'.
The solution was to trigger video.play() when pause is detected. I also found that it worked smoother not having the 'autoplay' attribute on the video and became jerky after multiple initialisations.
DOM:
<video id="video" loop muted>
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
</video>
JS:
video = jQuery('#video').get()[0];
video.addEventListener('loadeddata', function() {
video.play();
});
video.addEventListener('pause', function() {
video.play();
});
Also, for anyone wondering why I might want this ability, it is for a video playing on the background of a webpage, hence no need for user to play/pause it.
you can call video.play() before your ajax calling.
like
html
<video id="video">...</video>
JS
function play() {
$("#video")[0].play(); // call play here !!!
$.ajax(
"your url",
{your data},
function() {
$("#video")[0].play(); // usually we call play() here, but it will be pause beccause it can not be play if not in click or touch event sync
....
}
);
}
Your video tag has no ID. What if you had two <video> tags? You want:
<video id="blah"...
and then:
video = document.getElementById('blah');
Potentially it's a syntax error, because you seem to have some PHP leaking into the HTML in the form of '; ?> at the end of the poster and src attributes.
It seems like these answers do not work anymore. I tried the accepted one, and it didn't work.
It looks like Chrome can't find the video object and it stands as undefined.
You can do something else. Quite simple. You use the Global Event Handlers .ajaxSuccess as a marker for that the request has been handled and the video can now play.
In that way you are sure that the video object exist. And for Chrome you do a little if statement.
video = jQuery('#video').get()[0];
jQuery( document ).ajaxSuccess(function( event, xhr, settings ) {
if( video ) {
video.play();
} else {
// Chrome can't find the video object and throws a 'undefined'
// Therefore you have to activate the video manually
jQuery("#videoID")[0].play();
}
});
I started using this great plugin : http://blog.aaronvanderzwan.com/2012/07/maximage-2-0/
The problem is that when reaching a slide containing a video, sometimes it does not start (in chromium at least). No errors thrown, it just seems to be a random behavior regarding to the video loading.
Any idea if there's a way to keep firing the browser detection or to try forcing the video play with some plugin options/controls?
Also, I could not find a way to add a play button to the page to play/pause the video...
Found it, you need to get your element, and then call the play() function :
The html for the video :
<video id="vid_1" poster="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" width="640" height="360">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />
Your browser does not support HTML5 videos.
</video>
Then get the video element and fire the play :
//video play button
$('.play_button').click(function(){
var video = $('video#vid_1').get(0); //get the native browser source
if (video.paused) {
video.play(); //if paused, play
}
else{
video.pause(); //if playing, pause
}
});
So basically you can call it whenever you want...