Detect if HTML5 Video element is playing [duplicate] - javascript

This question already has answers here:
How to tell if a <video> element is currently playing?
(7 answers)
Closed 1 year ago.
I've looked through a couple of questions to find out if an HTML5 element is playing, but can't find the answer. I've looked at the W3 documentation and it has an event named "playing" but I can't seem to get it to work.
This is my current code:
var stream = document.getElementsByTagName('video');
function pauseStream() {
if (stream.playing) {
for (var i = 0; i < stream.length; i++) {
stream[i].pause();
$("body > header").addClass("paused_note");
$(".paused_note").text("Stream Paused");
$('.paused_note').css("opacity", "1");
}
}
}

It seems to me like you could just check for !stream.paused.

Check my answer at How to tell if a <video> element is currently playing?: MediaElement does not have a property that tells if it is playing or not. But you could define a custom property for it.
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function(){
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}
})
Now you can use it on video or audio elements like this:
if(document.querySelector('video').playing){
// Do anything you want to
}

Note : This answer was given in 2011. Please check the updated documentation on HTML5 video before proceeding.
If you just want to know whether the video is paused, use the flag stream.paused.
There is no property for a video element in getting its playing status. But there is one event "playing" which will be triggered when it starts to play. An Event called "ended" is also triggered when it stops playing.
So the solution is:
Declare one variable videoStatus.
Add event handlers for different events of video.
Update videoStatus using the event handlers.
Use videoStatus to identify the status of the video.
This page will give you a better idea about video events. Play the video on this page and see how the events are triggered.
http://www.w3.org/2010/05/video/mediaevents.html

jQuery(document).on('click', 'video', function(){
if (this.paused) {
this.play();
} else {
this.pause();
}
});

Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Html5 media events</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body >
<div id="output"></div>
<video id="myVideo" width="320" height="176" controls autoplay>
<source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">
</video>
<script>
var media = document.getElementById('myVideo');
// Playing event
media.addEventListener("playing", function() {
$("#output").html("Playing event triggered");
});
// Pause event
media.addEventListener("pause", function() {
$("#output").html("Pause event triggered");
});
// Seeking event
media.addEventListener("seeking", function() {
$("#output").html("Seeking event triggered");
});
// Volume changed event
media.addEventListener("volumechange", function(e) {
$("#output").html("Volumechange event triggered");
});
</script>
</body>
</html>

Best approach:
function playPauseThisVideo(this_video_id) {
var this_video = document.getElementById(this_video_id);
if (this_video.paused) {
console.log("VIDEO IS PAUSED");
} else {
console.log("VIDEO IS PLAYING");
}
}

I encountered a similar problem where I was not able to add event listeners to the player until after it had already started playing, so #Diode's method unfortunately would not work. My solution was check if the player's "paused" property was set to true or not. This works because "paused" is set to true even before the video ever starts playing and after it ends, not just when a user has clicked "pause".

You can use 'playing' event listener =>
const video = document.querySelector('#myVideo');
video.addEventListener("playing", function () {
// Write Your Code
});

Here is what we are using at http://www.develop.com/webcasts to keep people from accidentally leaving the page while a video is playing or paused.
$(document).ready(function() {
var video = $("video#webcast_video");
if (video.length <= 0) {
return;
}
window.onbeforeunload = function () {
var htmlVideo = video[0];
if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
return null;
}
return "Leaving this page will stop your video.";
};
}

a bit example
var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
if (audio.paused) {
audio.play()
} else {
audio.pause()
}

I just looked at the link #tracevipin added (http://www.w3.org/2010/05/video/mediaevents.html), and I saw a property named "paused".
I have ust tested it and it works just fine.

This is my code - by calling the function play() the video plays or pauses and the button image is changed.
By calling the function volume() the volume is turned on/off and the button image also changes.
function play() {
var video = document.getElementById('slidevideo');
if (video.paused) {
video.play()
play_img.src = 'img/pause.png';
}
else {
video.pause()
play_img.src = 'img/play.png';
}
}
function volume() {
var video = document.getElementById('slidevideo');
var img = document.getElementById('volume_img');
if (video.volume > 0) {
video.volume = 0
volume_img.src = 'img/volume_off.png';
}
else {
video.volume = 1
volume_img.src = 'img/volume_on.png';
}
}

I just did it very simply using onpause and onplay properties of the html video tag. Create some javascript function to toggle a global variable so that the page knows the status of the video for other functions.
Javascript below:
// onPause function
function videoPause() {
videoPlaying = 0;
}
// onPause function
function videoPlay() {
videoPlaying = 1;
}
Html video tag:
<video id="mainVideo" width="660" controls onplay="videoPlay();" onpause="videoPause();" >
<source src="video/myvideo.mp4" type="video/mp4">
</video>
than you can use onclick javascript to do something depending on the status variable in this case videoPlaying.
hope this helps...

My requirement was to click on the video and pause if it was playing or play if it was paused. This worked for me.
<video id="myVideo" #elem width="320" height="176" autoplay (click)="playIfPaused(elem)">
<source src="your source" type="video/mp4">
</video>
inside app.component.ts
playIfPaused(file){
file.paused ? file.play(): file.pause();
}

var video_switch = 0;
function play() {
var media = document.getElementById('video');
if (video_switch == 0)
{
media.play();
video_switch = 1;
}
else if (video_switch == 1)
{
media.pause();
video_switch = 0;
}
}

I just added that to the media object manually
let media = document.querySelector('.my-video');
media.isplaying = false;
...
if(media.isplaying) //do something
Then just toggle it when i hit play or pause.

a bit example when playing video
let v = document.getElementById('video-plan');
v.onplay = function() {
console.log('Start video')
};

Related

run 2 html video side by side at the same time JS

I would like to play 2 html video exactly at the same time (side-by-side).
I made a button which has a click EventListener on it. This listener trigger the 2 <video> tag to play it, but I think there is 150 ms a delay at the second play trigger.
index.html
<section>
<video src="source1" id="video1"></video>
<video src="source2" id="video2"></video>
<button id="play">Play</button>
</section>
and here is the basic script.js file.
const $video1 = document.getElementById('video1');
const $video2 = document.getElementById('video2');
const $play = document.getElementById('play');
const playVideo = () => {
$video1.play();
$video2.play();
};
$play.addEventListener('click', playVideo);
These 2 videos are almost the same, except the first video size is about 12MB and the other one is around 20MB
What I tried:
Tried to add a console.time('video') that could logs the delay between each play function call, but that can be different in each environment.
The only way I'm aware of about playing video in sync is to emit a custom event to sync the video in requestAnimationFrame:
var videos = {
a: Popcorn("#a"),
b: Popcorn("#b"),
},
scrub = $("#scrub"),
loadCount = 0,
events = "play pause timeupdate seeking".split(/\s+/g);
// iterate both media sources
Popcorn.forEach(videos, function(media, type) {
// when each is ready...
media.on("canplayall", function() {
// trigger a custom "sync" event
this.emit("sync");
// set the max value of the "scrubber"
scrub.attr("max", this.duration());
// Listen for the custom sync event...
}).on("sync", function() {
// Once both items are loaded, sync events
if (++loadCount == 2) {
// Iterate all events and trigger them on the video B
// whenever they occur on the video A
events.forEach(function(event) {
videos.a.on(event, function() {
// Avoid overkill events, trigger timeupdate manually
if (event === "timeupdate") {
if (!this.media.paused) {
return;
}
videos.b.emit("timeupdate");
// update scrubber
scrub.val(this.currentTime());
return;
}
if (event === "seeking") {
videos.b.currentTime(this.currentTime());
}
if (event === "play" || event === "pause") {
videos.b[event]();
}
});
});
}
});
});
scrub.bind("change", function() {
var val = this.value;
videos.a.currentTime(val);
videos.b.currentTime(val);
});
// With requestAnimationFrame, we can ensure that as
// frequently as the browser would allow,
// the video is resync'ed.
function sync() {
if (videos.b.media.readyState === 4) {
videos.b.currentTime(
videos.a.currentTime()
);
}
requestAnimationFrame(sync);
}
sync();
html{font-family:arial;}
<script src="https://static.bocoup.com/js/popcorn.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video height="180" width="300" id="a" controls>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.mp4"></source>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.ogv"></source>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.webm"></source>
</video>
<video height="180" width="300" id="b">
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.mp4"></source>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.ogv"></source>
<source src="https://videos.mozilla.org/serv/webmademovies/popcorntest.webm"></source>
</video>
<input type="range" value="0" id="scrub" />
Ref: https://bocoup.com/blog/html5-video-synchronizing-playback-of-two-videos
UPDATE
Both of the answers was correct.
What I didn't know, that one of the video file has sound, and the other don't. That caused the 150ms delay.
Solved it with ffmpeg. Create an .mp3 file with the sound (and play it with <audio>), and 2 .mp4 files without sound.
They are playing exactly at the same time now.
I will also add this link here, as evident someone had a very similar problem, albeit with audio
Run function after audio is loaded
It appears you are looking for this event listener "canplaythrough", check more in the link.
function checkAudio() {
audioElem.setAttribute("src", audioFile);
audioElem.addEventListener('canplaythrough', (event) => {
resultScreen.innerHTML = "loaded audio";
});
}

How to prevent "The play() request was interrupted by a call to pause()" error?

I made a website where if the user clicks, it plays a sound. To prevent the sound from overlapping, I had to add the code:
n.pause();
n.currentTime = 0;
n.play();
But that causes the error:
The play() request was interrupted by a call to pause()
To come up each time the sound event is triggered right after another trigger. The sounds still plays fine, but I want to prevent this error message constantly popping up. Any ideas?
I have encountered this issue recently as well - this could be a race condition between play() and pause(). It looks like there is a reference to this issue, or something related here.
As #Patrick points out, pause does not return a promise (or anything), so the above solution won't work. While MDN does not have docs on pause(), in the WC3 draft for Media Elements, it says:
media.pause()
Sets the paused attribute to true, loading the media resource if necessary.
So one might also check the paused attribute in their timeout callback.
Based on this great SO answer, here's a way you can check if the video is (or isn't) truly playing, so you can safely trigger a play() without the error.
var isPlaying = video.currentTime > 0 && !video.paused && !video.ended
&& video.readyState > video.HAVE_CURRENT_DATA;
if (!isPlaying) {
video.play();
}
Otherwise, #Patrick's answer should work.
After hours of seaching and working, i found perfect solution.
// Initializing values
var isPlaying = true;
// On video playing toggle values
video.onplaying = function() {
isPlaying = true;
};
// On video pause toggle values
video.onpause = function() {
isPlaying = false;
};
// Play video function
async function playVid() {
if (video.paused && !isPlaying) {
return video.play();
}
}
// Pause video function
function pauseVid() {
if (!video.paused && isPlaying) {
video.pause();
}
}
After that, you can toggle play/pause as fast as you can, it will work properly.
I have hit this issue, and have a case where I needed to hit pause() then play() but when using pause().then() I get undefined.
I found that if I started play 150ms after pause it resolved the issue. (Hopefully Google fixes soon)
playerMP3.volume = 0;
playerMP3.pause();
//Avoid the Promise Error
setTimeout(function () {
playerMP3.play();
}, 150);
try it
n.pause();
n.currentTime = 0;
var nopromise = {
catch : new Function()
};
(n.play() || nopromise).catch(function(){}); ;
I've just published an article about this exact issue at https://developers.google.com/web/updates/2017/06/play-request-was-interrupted that tells you exactly what is happening and how to fix it.
This solution helped me:
n.cloneNode(true).play();
Depending on how complex you want your solution, this may be useful:
var currentPromise=false; //Keeps track of active Promise
function playAudio(n){
if(!currentPromise){ //normal behavior
n.pause();
n.currentTime = 0;
currentPromise = n.play(); //Calls play. Will store a Promise object in newer versions of chrome;
//stores undefined in other browsers
if(currentPromise){ //Promise exists
currentPromise.then(function(){ //handle Promise completion
promiseComplete(n);
});
}
}else{ //Wait for promise to complete
//Store additional information to be called
currentPromise.calledAgain = true;
}
}
function promiseComplete(n){
var callAgain = currentPromise.calledAgain; //get stored information
currentPromise = false; //reset currentPromise variable
if(callAgain){
playAudio(n);
}
}
This is a bit overkill, but helps when handling a Promise in unique scenarios.
Solutions proposed here either didn't work for me or where to large,
so I was looking for something else and found the solution proposed by #dighan on bountysource.com/issues/
So here is the code that solved my problem:
var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
playPromise.catch(() => { media.play(); })
}
It still throws an error into console, but at least the video is playing :)
I have a similar issue, I think doing something like this is the easiest :
video.play().then(() => {
video.pause();
video.currentTime = 0;
video.play();
})
no matter if the video was playing or not, at the end the video will be paused without exception, then reset to zero and played again.
Calling play() even if the video is already playing is working fine, it returns a promise as expected.
Maybe a better solution for this as I figured out.
Spec says as cited from #JohnnyCoder :
media.pause()
Sets the paused attribute to true, loading the media resource if necessary.
--> loading it
if (videoEl.readyState !== 4) {
videoEl.load();
}
videoEl.play();
indicates the readiness state of the media
HAVE_ENOUGH_DATA = 4
Basically only load the video if it is not already loaded. Mentioned error occurred for me, because video was not loaded.
Maybe better than using a timeout.
removed all errors: (typescript)
audio.addEventListener('canplay', () => {
audio.play();
audio.pause();
audio.removeEventListener('canplay');
});
With live streaming i was facing the same issue. and my fix is this.
From html video TAG make sure to remove "autoplay"
and use this below code to play.
if (Hls.isSupported()) {
var video = document.getElementById('pgVideo');
var hls = new Hls();
hls.detachMedia();
hls.loadSource('http://wpc.1445X.deltacdn.net/801885C/lft/apple/TSONY.m3u8');
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function () {
video.play();
});
hls.on(Hls.Events.ERROR, function (event, data) {
if (data.fatal) {
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
// when try to recover network error
console.log("fatal network error encountered, try to recover");
hls.startLoad();
break;
case Hls.ErrorTypes.MEDIA_ERROR:
console.log("fatal media error encountered, try to recover");
hls.recoverMediaError();
break;
default:
// when cannot recover
hls.destroy();
break;
}
}
});
}
It looks like a lot of programmers encountered this problem.
a solution should be quite simple. media element return Promise from actions so
n.pause().then(function(){
n.currentTime = 0;
n.play();
})
should do the trick
Chrome returns a Promise in newest versions.
Otherwise, simply:
n.pause();
n.currentTime = 0;
setTimeout(function() {n.play()}, 0);
I have the same issue, finally i solve by:
video.src = 'xxxxx';
video.load();
setTimeout(function() {
video.play();
}, 0);
This piece of code fixed for me!
Modified code of #JohnnyCoder
HTML:
<video id="captureVideoId" muted width="1280" height="768"></video>
<video controls id="recordedVideoId" muted width="1280"
style="display:none;" height="768"></video>
JS:
var recordedVideo = document.querySelector('video#recordedVideoId');
var superBuffer = new Blob(recordedBlobs, { type: 'video/webm' });
recordedVideo.src = window.URL.createObjectURL(superBuffer);
// workaround for non-seekable video taken from
// https://bugs.chromium.org/p/chromium/issues/detail?id=642012#c23
recordedVideo.addEventListener('loadedmetadata', function () {
if (recordedVideo.duration === Infinity) {
recordedVideo.currentTime = 1e101;
recordedVideo.ontimeupdate = function () {
recordedVideo.currentTime = 0;
recordedVideo.ontimeupdate = function () {
delete recordedVideo.ontimeupdate;
var isPlaying = recordedVideo.currentTime > 0 &&
!recordedVideo.paused && !recordedVideo.ended &&
recordedVideo.readyState > 2;
if (isPlaying) {
recordedVideo.play();
}
};
};
}
});
I've fixed it with some code bellow:
When you want play, use the following:
var video_play = $('#video-play');
video_play.on('canplay', function() {
video_play.trigger('play');
});
Similarly, when you want pause:
var video_play = $('#video-play');
video_play.trigger('pause');
video_play.on('canplay', function() {
video_play.trigger('pause');
});
Reason one - calling pause without waiting for play promise to resolve
too many answer fo this scenario, so I will just refer to the best doc for that issue:
https://developers.google.com/web/updates/2017/06/play-request-was-interrupted
Reason two - calling play when the tab is not focused
In this case, the browser could interrupt the play by calling pause when the tab is not focus. in order to save resources for the active tab.
So you could just wait for the tab to be focused before calling play:
async function waitForTabFocus() {
return new Promise((resolve, reject) => {
const onFocus = () => { resolve(); window.removeEventListener('focus', onFocus) };
window.addEventListener('focus', onFocus)
})
}
if (!document.hasFocus()) await this.waitForTabFocus();
videoEl.play();
Here is another solution if the reason is that your video download is super slow and the video hasn't buffered:
if (videoElement.state.paused) {
videoElement.play();
} else if (!isNaN(videoElement.state.duration)) {
videoElement.pause();
}
here is a solution from googler blog:
var video = document.getElementById('#video')
var promise = video.play()
//chrome version 53+
if(promise){
promise.then(_=>{
video.pause()
})
}else{
video.addEventListener('canplaythrough', _=>{
video.pause()
}, false)
}
All new browser support video to be auto-played with being muted only so please put Something like the this
<video autoplay muted="muted" loop id="myVideo">
<source src="https://w.r.glob.net/Coastline-3581.mp4" type="video/mp4">
</video>
URL of video should match the SSL status if your site is running with https then video URL should also in https and same for HTTP
The cleanest and simplest solution:
var p = video.play();
if (p !== undefined) p.catch(function(){});
Here's my solution (tongue-in-cheek answer):
Sentry.init({
// ...
ignoreErrors: [
'AbortError: The play() request was interrupted',
],
});
This error is pointless. If play() was interrupted, then it was interrupted. No need to throw an error about it.
I ran into the same issue and resolved it by dynamically adding the autoplay attribute rather than using play(). That way the browser figured out to play without running into the race condition.
Trying to get an autoplaying video to loop by calling play() when it ends, the timeout workaround did not work for me (however long the timeout is).
But I discovered that by cloning/replacing the video with jQuery when it ended, it would loop properly.
For example:
<div class="container">
<video autoplay>
<source src="video.mp4" type="video/mp4">
</video>
</div>
and
$(document).ready(function(){
function bindReplay($video) {
$video.on('ended', function(e){
$video.remove();
$video = $video.clone();
bindReplay($video);
$('.container').append($video);
});
}
var $video = $('.container video');
bindReplay($video);
});
I'm using Chrome 54.0.2840.59 (64-bit) / OS X 10.11.6
I think they updated the html5 video and deprecated some codecs.
It worked for me after removing the codecs.
In the below example:
<video>
<source src="sample-clip.mp4" type="video/mp4; codecs='avc1.42E01E, mp4a.40.2'">
<source src="sample-clip.webm" type="video/webm; codecs='vp8, vorbis'">
</video>
must be changed to
<video>
<source src="sample-clip.mp4" type="video/mp4">
<source src="sample-clip.webm" type="video/webm">
</video>
When you see an error with Uncaught (in promise) This just means that you need to handle the promise with a .catch() In this case, .play() returns a promise. You can decide if you want to log a message, run some code, or do nothing, but as long as you have the .catch() the error will go away.
var n = new Audio();
n.pause();
n.currentTime = 0;
n.play().catch(function(e) {
// console.log('There was an error', e);
});
I have used a trick to counter this issue.
Define a global variable var audio;
and in the function check
if(audio === undefined)
{
audio = new Audio(url);
}
and in the stop function
audio.pause();
audio = undefined;
so the next call of audio.play, audio will be ready from '0' currentTime
I used
audio.pause();
audio.currentTime =0.0;
but it didn't work.
Thanks.

play/pause video onclick firefox

I want videos to play/pause when you click on them. Firefox has this behaviour by default. Chrome does not. The simple solution I came up with was setting a click event with jQuery.
var video = $('#myVideo');
var videoDomObj = video.get(0);
//click event for the video itself
video.on('click', function(e){
//when video is clicked it should be paused when playing and vise versa
if (videoDomObj.paused){
videoDomObj.play();
} else{
videoDomObj.pause();
}
});
jsfiddle
This will work in IE and Chrome. However, this will result in a conflict in Firefox, since it will instantly call the default event afterwards and will not play the video at all. e.preventDefault() fixes this problem, but will break all the other controls in Firefox. While they still work, they will play/pause the video. Is there an easy solution for this?
In fact the raw code worked like a charm:
document.getElementById('myVideo').onclick = function(e) {
e.preventDefault();
if (this.paused){
this.play();
} else{
this.pause();
}
}
The jQuery equivalent should be:
jQuery('#myVideo').on('click', function(e) {
e.preventDefault();
if (this.paused){
this.play();
} else{
this.pause();
}
});
But as you said that breaks the video controlls, desired and simplest solution for this could be selecting a parent element (or adding a container, if required):
var video = document.getElementById('myVideo');
video.parentElement.onclick = function(e) {
if (video.paused){
video.play();
} else{
video.pause();
}
}
jQuery:
var $video = jQuery('#myVideo'), video = $video.get(0);
$video.parent().on('click', function(e) {
if (video.paused){
video.play();
} else{
video.pause();
}
});
The only solution I found was to detect the browser for this special case, since the problem only occurs in firefox and it has this feature by default anyway.
jsfiddle
//jQuery video element
var video = $('#myVideo');
//DOM element for HTML5 media events
var videoDomObj = video.get(0);
//detect if firefox
var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
//only bind click event if not firefox to prevent broken controls - firefox pauses/plays videos on click by default anyway
if (!is_firefox){
video.on('click', function(e){
//when video is clicked it should be paused when playing and vise versa
if (videoDomObj.paused){
videoDomObj.play();
} else{
videoDomObj.pause();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="myVideo" width="100%" controls>
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>

Run a function a few seconds before video ends using JavaScript

I have a video the being played. How can I call a function 5 seconds before the end of the video?
I thought to put a timer when I start the video, the problem is that the user can control the video, and stop it and play again how many times he wants, so the timer is getting ineffective.
Examples would be very nice!
-----EDIT-----
this is an example to a code i'm using:
video = document.createElement("video");
video.setAttribute("id", id);
video.src = url;
video.onended = function(e) {
var playlistName = getPlaylistName();
findNextSongToPlay(playlistName, playNextSong);
};
I want the "onended" event to be called not in the end, but 5 seconds before..
So I need to change it a little bit..
Again, Thanks a lot!
Here is a demo for you
Edit: Updated Demo.
window.onload=function(){
video = document.createElement("video");
video.setAttribute("id", "Myvideo");
video.setAttribute("controls", "controls");
video.src = "http://www.w3schools.com/html/mov_bbb.mp4";
video.addEventListener("timeupdate", myfunc,false);
document.body.appendChild(video);
}
function myfunc(){
if(this.currentTime > this.duration-5){
//Less than 5 seconds to go. Do something here.
//---- For Demo display purposes
document.getElementById('Example').innerHTML="Less than 5 seconds to go!";
//---------
} //End Of If condition.
//---- For Demo display purposes
else{document.getElementById('Example').innerHTML="";}
//---------
}
<div id="Example"></div>
Since your player is dynamically created you can use:
video = document.createElement("video");
video.setAttribute("id", id);
video.src = url;
//Add the event Listener
video.addEventListener("timeupdate", myfunc,false);
video.onended = function(e) {
var playlistName = getPlaylistName();
findNextSongToPlay(playlistName, playNextSong);
};
and that should call this function
function myfunc(){
if(this.currentTime > this.duration-5){
//Do something here..
}
}
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
Sample with HTML5 player.
At most 100 milliseconds of difference can occur, not exactly 5 seconds.
But you can tune the script.
You can paste this code here to try it:
http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_video_all
<html>
<body>
<video id="vid" width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<script>
var callOnce = true;
function monitorVideo() {
if ((vid.duration - vid.currentTime) < 5)
if (callOnce) {
myFunction();
callOnce = false;
}
}
function myFunction() {
console.log('5 seconds');
}
setInterval(monitorVideo, 100);
</script>
</body>
</html>
Tell us what video player you are using.
If it is custom put an id on part that says how far in to the video you are and say
if (document.getElementById("bla").innerhtml === whatever 5 seconds before the end of the video is)
function();

how to change vimeo video source to local mp4 video using javascript

I'm trying to make a video player which contains vimeo and local video but I'm dont know how to switch the video source to local video if the vimeo video fails to play.Im using video.js.any help please :)
here is my coding:
HTML
<video id="vid1" src="" class="video-js vjs-default-skin" controls preload="auto" width="640" height="360">
Javascript:
videojs('vid1', { "techOrder": ["vimeo"], "src": "https://vimeo.com/63186969" }).ready(function() {
// You can use the video.js events even though we use the vimeo controls
// As you can see here, we change the background to red when the video is paused and set it back when unpaused
this.on('pause', function() {
document.body.style.backgroundColor = 'red';
});
this.on('play', function() {
document.body.style.backgroundColor = '';
});
// You can also change the video when you want
// Here we cue a second video once the first is done
this.one('ended', function() {
this.src('http://video-js.zencoder.com/oceans-clip.mp4');
this.play();
});
i make some changes to my js but still unable to change.im new to javascript..please help me :)
Javascript:
videojs('vid2', { "techOrder": ["vimeo"], "src": "https://vimeo.com/63186969" }).ready(function() {
// You can use the video.js events even though we use the vimeo controls
// As you can see here, we change the background to red when the video is paused and set it back when unpaused
this.on('pause', function() {
document.body.style.backgroundColor = 'red';
});
this.on('play', function() {
document.body.style.backgroundColor = '';
});
// You can also change the video when you want
// Here we cue a second video once the first is done
this.one('ended', function() {
this.src('http://vimeo.com/79380715');
this.play();
});
myPlayer.src("http://video-js.zencoder.com/oceans-clip.mp4");
var myPlayer = videojs('vid2');
myPlayer.ready(function(){ /*Video is ready*/ });
myPlayer.error(function(){ /*An error happened*/ });
mpPlayer.play();
]);
So there are the 2 events:
var myPlayer = videojs('example_video_1');
myPlayer.ready(function(){ /*Video is ready*/ });
myPlayer.error(function(){ /*An error happened*/ });
More api info here : https://github.com/videojs/video.js/blob/master/docs/api/vjs.Player.md

Categories