On my site, on background plays video. How i can make resuming video on the same point, when i am going to another page? Pages refreshing with ajax.
I tried to solve it by little script on the main page:
<script>
var vid = document.getElementById("video");
vid.addEventListener("canplay", function(e) {
var currTime = this.currentTime;
this.play();
}, false
);
</script>
Another script, on the other html page, where i want to continue my video:
<script>
var vid = document.getElementById("myVideo");
vid.addEventListener("canplay", function(e) {
this.currentTime = currTime;
this.play();
}, false
);
</script>
I am getting next error:
Uncaught ReferenceError: currTime is not defined
at HTMLVideoElement.<anonymous>
Am i right with this solution? Will it work If i could fix this error? If answer: yes, how i can globalize this "currTime"?
Thank you.
Updated:
HTML code for video:
<video loop muted autoplay poster="../static/images/wallpaper.png" class="fullscreen-bg__video" id="video">
<source src="../static/videos/wallpaper.mp4" type="video/mp4">
<source src="../static/videos/wallpaper.webm" type="video/webm">
</video>
.fullscreen-bg__video {
position: absolute;
top: 0;
left: 0;
width: 100%;
margin:0;
}
on the page, where i am getting paused video the same code but with another id.
<script>
var vid = document.getElementById("video");
vid.addEventListener("canplay", function(e) {
localStorage.setItem("videoTime", this.currentTime);
this.play();
}, false
);
</script>
NOTE: localStorage.setItem("videoTime", this.currentTime) is only done ONCE. You could set the time with setInterval() every second to a new value.
setInterval(() => {localStorage.setItem("videoTime", this.currentTime);},1000);
After reload get item with:
<script>
var vid = document.getElementById("myVideo");
vid.addEventListener("canplay", function(e) {
if(localStorage.getItem("videoTime") !== null) {
this.currentTime = localStorage.getItem("videoTime");
}
this.play();
}, false
);
</script>
UPDATE:
Tested it on my machine. Works with any .html file. Just paste this as script:
<script>
window.onload = () => {
var vid = document.getElementById("video");
if(localStorage.getItem("videoTime") !== null && localStorage.getItem("videoTime") !== undefined) {
vid.currentTime = localStorage.getItem("videoTime"); }
setInterval(() => {localStorage.setItem("videoTime", vid.currentTime);},1000); }
</script>
execute the script after window has loaded.
get vid as HTMLElement
check if localStorage entry with the key vidTime exists.
if yes, set vid time with vid.currentTime = localStorage.getItem("videoTime");
update every second new videoTime: setInterval(() => {localStorage.setItem("videoTime", vid.currentTime);},1000);
Related
How do I set the current time for an audio object when a html page loads? This is what I am currently doing:
var a = document.getElementById("myAudio");
a.addEventListener("timeupdate", function() {
console.log(this.currentTime);
// do other stuff like display the current time
}
var isCurrentTimeSetOnStartup = false;
a.addEventListener("canplay", function() {
if (isCurrentTimeSetOnStartup == false){
this.currentTime = startTime;
isCurrentTimeSetOnStartup = true;
}
});
which I think is ugly. If I don't have the isCurrentTimeSetOnStartup guard then the two events trigger each other.
You can place your script at the bottom of the <body> tag and then use the following code to set the currentTime of your Audio Source.
let a = document.querySelector('#myAudio');
let startTime = 2;
a.addEventListener('canplay', function handler() {
// Time in seconds
this.currentTime = startTime;
// Remove the event listener
this.removeEventListener('canplay', handler);
});
a.addEventListener('timeupdate', function() {
//Time in seconds
console.log(this.currentTime);
});
// Play on DOM-Load
a.play();
<!--http://picosong.com/wwPMj/-->
<audio id="myAudio" controls>
<source src="https://www.computerhope.com/jargon/m/example.mp3" type="audio/mpeg">
Your browser does not support HTML5 video.
</audio>
When I hover my video control bar in Chrome, Safari it shows up. But when I hover that in firefox, it's not showing. I don't know if my js code doesn't support firefox. But when I inspect it in firefox, the controls keep appearing and disappearing. Below is my code. Can anyone help me with this? Thank you.
HTML
<video poster="http://dummyimage.com/320x205/852285/fff" preload="auto">
<source type="video/mp4" src="http://www.w3schools.com/html/movie.mp4" />
</video>
JS
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/mediaelement/2.13.1/js/mediaelement.js'></script>
// Video Player
function videoPlayer() {
// Exit full screen when video is done playing
var video = document.getElementsByTagName("video")[0];
video.addEventListener("ended", function(e) {
video.webkitExitFullScreen()
});
var player = $('.video-player'),
controls = player.find('.vid-play-btn-wrap'),
wrapper = player.find('video'),
video = player.find('video').get(0),
isPlaying = false,
settings = {},
media = new MediaElement(video, settings),
$media = $(media);
$media.on('play', _playHandler);
$media.on('pause', _pauseHandler);
$media.on('ended', _endedHandler);
player.click(_togglePlayPause);
player.hover(_mouseOverHandler, _mouseOutHandler);
function _togglePlayPause() {
isPlaying ? media.pause() : media.play();
}
function _mouseOverHandler() {
if(!isPlaying) { return; }
// controls.fadeIn('fast');
}
function _mouseOutHandler() {
if(!isPlaying) { return; }
// controls.fadeOut('fast');
}
function _endedHandler() {
isPlaying = false;
video.load();
controls.show();
}
function _playHandler() {
isPlaying = true;
controls.hide();
}
function _pauseHandler() {
isPlaying = false;
}
$('video').hover(function toggleControls() {
if (this.hasAttribute("controls")) {
this.removeAttribute("controls")
} else {
this.setAttribute("controls", "controls")
}
});
}
you have this in your script:
player.hover(_mouseOverHandler, _mouseOutHandler);
So BOTH functions are executed on hover (which explains the appearing and disappearing). It might be better to create ONE function that contains both things you want in an if/else statement
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();
I need a video to start at a specific time and I need that time to be determined by the value written into the page's URL.
I have this video element:
<video id="vid1" width="auto" height="auto" controls autoplay>
<source src="video1.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
This function successfully cues the video to 50 seconds:
<script>
document.getElementById('vid1').addEventListener('loadedmetadata', function() {
this.currentTime = 50;
}, false);
</script>
Let's say my URL is http://www.mywebaddress.com/video1.html?50
I want to grab the value "50" from the URL and pass it into my function so that I can dynamically change the time to which the video cues.
I've got this function to grab the value from the URL:
<script>
function GetUrlValue(VarSearch){
var TimeCode = window.location.search.substring(1);
}
</script>
How do I rewrite the cue function now so that it sets the value to whatever value chosen in the URL?
Thanks in advance.
You could try this :
<script>
var TimeCode;
function GetUrlValue(){
TimeCode = parseInt(window.location.href.split("?")[1]);
}
</script>
And then :
GetUrlValue();
document.getElementById('vid1').addEventListener('loadedmetadata', function() {
this.currentTime = TimeCode;
}, false);
You can either change the call of this.currentTime to
document.getElementById('vid1').addEventListener('loadedmetadata', function() {
this.currentTime = window.location.search.substring(1);
}, false);
or in sticking to your variable mechanism you could do
var TimeCode = window.location.search.substring(1);
document.getElementById('vid1').addEventListener('loadedmetadata', function() {
this.currentTime = TimeCode;
}, false);
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')
};