HTML5 Video: Fire play at specific video time - javascript

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();
};

Related

video won't pause using Javascript

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);

Changing html5 video source with preloading

I'm setting up a video portfolio site to showcase different concepts for software devs, and there are often multiple versions of the same video.
I wrote the following javascript to change videos and it works fine locally, the problem is that once its hosted changing videos breaks the video player. I'm guessing the cause is because the new video is not loaded. Any ideas?
function switcher(wrapper, e, source, container, video){
//get current version and turn off its style
var off = document.getElementById(wrapper).getElementsByClassName("versionActive")[0];
off.className = "version";
//turn on the new button
e.className = "versionActive";
var videoSource = document.getElementById(source);
var videoContainer = document.getElementById(container);
lastPlayingVideo.currentTime = 0;
lastPlayingVideo.pause();
lastPlayingVideo = videoContainer;
videoSource.setAttribute('src', video);
videoContainer.load();
videoContainer.play();
}
The html for the video player looks like this:
<video id="container1" controls="" loop="" preload="auto" width="1280" height="720">
<source id="video1" src="videos/Reminder.mp4" type="video/mp4">
</video>
Try :
videoContainer.addEventListener('canplay', function() {
videoContainer.play();
videoContainer.removeEventListener('canplay');
});
videoSource.setAttribute('src', video);
videoContainer.load();
canplay is fired when the browser supposes you have received enough of the file and you can continue playing it considering your connection speed.

Set Duration of video playback with HTML5

I've got a simple HTML5 Video Player that is using TimeJump.js (http://davatron5000.github.io/TimeJump/) to allow for direct jumping to specific time codes.
I.E. Jump to the 25th minute of the video.
I would like to add a limit on the duration of the video played. So, the user can only watch 60 seconds of video at a time. I cannot use the Media URL spec (i.e. #t=25,85) because the beginning of the video will change based on the URL string entered by the user (using TimeJump.js to jump to the point in the video)
Any ideas on how to limit the duration of video played?
thanks.
I never used TimeJump.js but you can listen to the timeupdate event of the media element (audio and video).
var video = document.querySelector('video');
video.addEventListener('timeupdate', function() {
// don't have set the startTime yet? set it to our currentTime
if (!this._startTime) this._startTime = this.currentTime;
var playedTime = this.currentTime - this._startTime;
if (playedTime >= 10) this.pause();
});
video.addEventListener('seeking', function() {
// reset the timeStart
this._startTime = undefined;
});
<video controls="true" height="200" width="300">
<source type="video/ogg" src="http://media.w3.org/2010/05/bunny/movie.ogv">
<source type="video/mp4" src="http://media.w3.org/2010/05/bunny/movie.mp4">
</video>

Play full HTML5 video and then loop a section of it

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

Maximage 2.0 - HTML5 Video random start

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...

Categories

Resources