how to create a timer on a video with JavaScript? - javascript

I wrote the code like this, and the play button works but the timer does not.
<input type="button" id="play" onclick="videoplay();" value=">"/>
....
<span id="timer">0%</span>
....
function videoplay() {
var video = document.getElementById("video");
var button = document.getElementById("play");
if (video.paused) {
video.play();
button.value = "||";
var timer = getElementbyId("timer");
var update = setInterval(function () {
timer.textContent = Math.round(video.currentTime / video.duration * 100) + "%";
}, 500);
} else {
video.pause();
button.value = ">";
if (update)
clearInterval(update);
}
}

timer.innerText = Math.round(video.currentTime / video.duration * 100) + "%";

Related

How can i play multiple audio file gotten from a database without using same audio id

I got this code here on stack overflow which is a custom audio player. But then modified the code to fetch audio from my database. The problem am having is only the first song gotten from my database is been played.
This is my code that displays the audio with the controls
<?php
require '../db.php';
$sql = "select * from songs order by song_id asc";
$sql_query = mysqli_query($con,$sql);
$i=0;
while ($row = mysqli_fetch_array($sql_query)) {
$image = $row['song_image'];
$song_name = $row['song_name'];
$audio = $row['song_audio'];
?>
<audio controls="controls" class='podcast-audio hide' id="player">
<source src="../Admin/Song/songAudio/<?php if(isset($audio)){ echo $audio;}?>" type="audio/mpeg"
/>
</audio>
<div id="audio-player">
<div id="controls">
<i id="play" class="fa fa-play cursor-pointer"></i>
<span id="time" class="time">00:00</span>
<div id="progressbar" class='cursor-pointer ui-progressbar'></div>
<span id="end-time" class="time">00:00</span>
<i id="mute" class="fa fa-volume-up cursor-pointer"></i>
<div id="volume" class='cursor-pointer ui-progressbar'></div>
</div>
</div>
<?php
$i++;
}
?>
This is my javascript code responsible for playing the audio
$(document).ready(function() {
var audio_player = $("#audio-player");
var play_button = $('#play');
var progress_bar = $("#progressbar");
var time = $("#time");
var mute_button = $('#mute');
var volume_bar = $('#volume');
var more_info = $('#more-info-box');
var player = $('#player')[0];
var duration = 0;
var volume = 0.5;
var end_time = $('#end-time');
player.onloadedmetadata = function () {
duration = player.duration;
var minutes = parseInt(duration / 60, 10);
var seconds = parseInt(duration % 60);
// finding and appending full duration of audio
end_time.text(minutes + ':' + seconds);
console.log('ddd', progress_bar)
progress_bar.progressbar("option", { 'max': duration });
};
player.load();
player.volume = 0.5;
player.addEventListener("timeupdate", function () {
progress_bar.progressbar('value', player.currentTime);
time.text(getTime(player.currentTime));
}, false);
volume_bar.progressbar({
value: player.volume * 100,
});
volume_bar.click(function (e) {
var info = getProgressBarClickInfo($(this), e);
volume_bar.progressbar('value', info.value);
player.volume = info.value / info.max;
});
progress_bar.progressbar({
value: player.currentTime,
});
progress_bar.click(function (e) {
var info = getProgressBarClickInfo($(this), e);
player.currentTime = player.duration / info.max * info.value;
});
play_button.click(function () {
player[player.paused ? 'play' : 'pause']();
$(this).toggleClass("fa-play", player.paused);
$(this).toggleClass("fa-pause", !player.paused);
});
mute_button.click(function () {
if (player.volume == 0) {
player.volume = volume;
} else {
volume = player.volume;
player.volume = 0;
}
volume_bar.progressbar('value', player.volume * 100);
$(this).toggleClass("fa-volume-up", player.volume != 0);
$(this).toggleClass("fa-volume-off", player.volume == 0);
});
more_info.click(function () {
audio_player.animate({
height: (audio_player.height() == 50) ? 100 : 50
}, 1000);
});
});
function getTime(t) {
var m = ~~(t / 60), s = ~~(t % 60);
return (m < 10 ? "0" + m : m) + ':' + (s < 10 ? "0" + s : s);
}
function getProgressBarClickInfo(progress_bar, e) {
var offset = progress_bar.offset();
var x = e.pageX - offset.left; // or e.offsetX (less support, though)
var y = e.pageY - offset.top; // or e.offsetY
var max = progress_bar.progressbar("option", "max");
var value = (x * max) / progress_bar.width();
return { x: x, y: y, max: max, value: value };
}
It looks like you're using the same javascript/HTML ID on each of the play, pause buttons.
Eg. if you're returning 3 songs, then the id within Javascript will be appearing 3 times...
<audio ... id="player">
<audio ... id="player">
<audio ... id="player">
So, as an ID on a page can only be created once, when your javascript function goes to find the song, it finds the first ID, gets it's the source and plays it.
I'd suggest that you either:
I can see you're using a counter. Change the ID of each player id to be player1, player2, etc and refer to that, OR
Get your player code to search by class instead of by id. Eg.
var player = $('.podcast-audio')[0][0];

toggle volume in html5 video

I am trying to build HTML5 video player but the volume seems to be currently an issue for me.
I want the volume bar to change depending on the user clicking on the volume icon. Currently if you click on the volume button it will set the volume value to 0 but then if I click again it should set it to 1. Unfortunately, it stays the whole time in the 0 and doesn't change as I click. My js looks like:
window.onload = function() {
//video
var video = document.getElementsByClassName("js-video-container__video")[0];
//Buttons
var playButton = document.getElementsByClassName("js-video-controls__play-pause")[0];
var timer = document.getElementsByClassName("js-video-controls__timer")[0];
var seconds = document.getElementsByClassName("js-video-controls__timer__seconds")[0];
var minutes = document.getElementsByClassName("js-video-controls__timer__minutes")[0];
var fullScreenButton = document.getElementsByClassName("js-video-controls__full-screen")[0];
var volumeButton = document.getElementsByClassName("js-video-controls__volume-icon")[0];
//sliders
var seekBar = document.getElementsByClassName("js-video-controls__seek-bar")[0];
var volumeBar = document.getElementsByClassName("js-video-controls__volume-bar")[0];
//event listener for the play and pause button
playButton.addEventListener("click", function() {
if (video.paused == true) {
video.play();
//button text will change to Pause
playButton.style.backgroundImage='url("https://image.flaticon.com/icons/svg/64/64485.svg")';
playButton.style.backgroundSize="13px";
} else {
//pause the video
video.pause();
//button will update its text to play
playButton.style.backgroundImage='url("https://image.flaticon.com/icons/svg/149/149657.svg")';
playButton.style.backgroundSize="13px";
// playButton.style.backgroundPositionY="4px";
}
});
// Event listener for the full-screen button
fullScreenButton.addEventListener("click", function() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen(); // Firefox
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen(); // Chrome and Safari
}
});
// Event listener for the volume button
volumeButton.addEventListener("click", function() {
if (volumeBar.value !== 0) {
console.log("clicked the right button");
volumeBar.value = 0;
volumeButton.style.backgroundImage='url("https://image.flaticon.com/icons/svg/2089/2089815.svg")';
volumeButton.style.backgroundSize="13px";
} else {
volumeBar.value = 1;
}
});
//event listener for the change bar
seekBar.addEventListener("change", function() {
//calculate the new time
var time = video.duration * (seekBar.value / 100);
//update the video time
video.currentTime = time;
});
//the change bar will move as the video plays
video.addEventListener("timeupdate", function() {
//Calculate the slider value
var value = (100 / video.duration) * video.currentTime;
//Update the slider value
seekBar.value = value;
console.log(video.currentTime);
console.log(video.duration)
seconds.innerHTML = 0 + ":" + Math.floor(video.currentTime) + " / ";
minutes.innerHTML = Math.floor(video.duration / 60) + ":00";
});
//pause the video when the slider handle is being dragged
seekBar.addEventListener("mousedown", function() {
video.pause();
});
//play the video when the
seekBar.addEventListener("mouseup", function() {
video.play();
});
volumeBar.addEventListener("change", function() {
//update the video volume
video.volume = volumeBar.value;
});
}
And my html is currently:
<div class="video-controls">
<button type="button" class="video-controls__play-pause js-video-controls__play-pause"></button>
<input type="range" class="video-controls__seek-bar js-video-controls__seek-bar" value="0">
<div class="video-controls__space"></div>
<div class="video-controls__timer js-video-controls__timer">
<div class="video-controls__timer__seconds js-video-controls__timer__seconds">0:00 /</div>
<div class="video-controls__timer__minutes js-video-controls__timer__minutes"> 0:00</div>
</div>
<button class="video-controls__volume-icon js-video-controls__volume-icon"> </button>
<input type="range" class="video-controls__volume-bar js-video-controls__volume-bar" min="0" max="1" step="0.1" value="1">
<button type="button" class="video-controls__full-screen js-video-controls__full-screen"></button>
</div>
</div>
hey here's my solution I think this is what you want :)
https://jsfiddle.net/nb5Lcmvh/
var volumeButton = $(".js-video-controls__volume-icon");
//sliders
var seekBar = $(".js-video-controls__seek-bar");
var volumeBar = $(".js-video-controls__volume-bar");
$(volumeButton).click(function(){
if ($(volumeBar).val() != 0) {
$(volumeBar).val(0);
}
else{
$(volumeBar).val(1);
}
});

I need a timer to temporarily disable mouseover event

I'm looking for a simple way to temporarily disable a mouseover event, for literally 1000 miliseconds. All my attempts to do so, have so-far failed. I am trying to stop my images from flickering when the mouse enters several times as it hovers over the edge of the div. Here is my code:
var ranNum, result_10, resultFloor, piccy, audio;
function myFunction() {
ranNum = Math.random();
result_10 = (ranNum * 5) + 1;
resultFloor = Math.floor(result_10);
piccy = "<img src=\"random_images/" + resultFloor + ".gif\" />";
document.getElementById("demo").innerHTML = piccy;
audio = document.getElementById("audio");
audio.play();
}
<div id="container">
<div id="demo" onmouseenter="myFunction()">This</div>
<audio id="audio" src="pop.wav" ></audio>
</div>
This will stop the flicker:
var ranNum, result_10, resultFloor, piccy, audio;
var isPlaying = false;
var audio = document.getElementById("audio");
function myFunction() {
if (!isPlaying) {
isPlaying = true;
ranNum = Math.random();
result_10 = (ranNum * 5) + 1;
resultFloor = Math.floor(result_10);
piccy = "<img src=\"http://d2.alternativeto.net/dist/icons/cloudapp_2094.png?width=64&height=64&mode=crop&upscale=false\" />";
document.getElementById("demo").innerHTML = piccy;
// check every 1/2 second to see if the audio has ended
var t = setInterval(function() {
console.log(audio.ended);
if (audio.ended) {
isPlaying = false;
clearInterval(t);
}
}, 500);
audio.play();
}
}
<div id="container">
<div id="demo" onmouseenter="myFunction()">This</div>
<audio id="audio" src="http://freewavesamples.com/files/Casio-MT-45-Pops.wav" ></audio>
</div>
var myFunctionDisabled = null;
function disableMyFunction() {
clearTimeout(myFunctionDisabled);
myFunctionDisabled = setTimeout(function() { myFunctionDisabled = false; }, 1000);
}
function myFunction() {
if (myFunctionDisabled) return;
...
}
Here's a quick and dirty approach. Simply uses a variable referencing a function, and changes the reference to point to a function that does nothing, then back to the original function.
I agree with Kosch's suggestion of using the underscore/lodash debounce function if you're already using those libraries or if you see them helping you in more than just this one case.
var ranNum, result_10, resultFloor, piccy, audio;
function myFunction() {
disableMouseOverHandler();
ranNum = Math.random();
result_10 = (ranNum * 5) + 1;
resultFloor = Math.floor(result_10);
piccy = "<img src=\"random_images/" + resultFloor + ".gif\" />";
document.getElementById("demo").innerHTML = piccy;
audio = document.getElementById("audio");
audio.play();
}
function doNothing() {
}
var mouseOverHandler = myFunction;
function disableMouseOverHandler() {
mouseOverHandler = doNothing;
setTimeout(function(){ mouseOverHandler = myFunction; }, 3000);
//I used 3000ms (3 seconds) to make it more pronounced.
}
<div id="container">
<div id="demo" onmouseenter="mouseOverHandler()">This</div>
<audio id="audio" src="pop.wav" ></audio>
</div>

Replace Javascript ID's with Clases for HTML5 Video Controls

I've replaced all ID's with Classes in the HTML and in the Javascript for the Video Player, but it's still doesn't work. I"m a newbie in javascript so I'm going to need some help to figure out why it's not runing the way that it should.
Here's a fiddle:
http://jsfiddle.net/k37Bs/
The updated JS suggested by Chris Ferdinandi still doesnt work. The JS is pasted below:
I replaced the Add Event Listener code completely and removed the setobject reference section of codes, still no dice. Any further help will be greatly appreciated.
//----------------------------Video Player--------------------------------------
var vid, playbtn, seekslider, curtimetext, durtimetext, mutebtn, volumeslider, fullscreenbtn;
//--------Functions------------------------------
// Initialize Player
function intializePlayer(){
window.onload = intializePlayer;
// Play/Pause Function
function playPause(){
if(vid.paused){
vid.play();
playbtn.style.background = "url(pause.png)";
} else { vid.pause();
playbtn.style.background = "url(play.png)";
}
}
// Video Seek Function
function vidSeek(){
var seekto = vid.duration * (seekslider.value / 100);
vid.currentTime = seekto;
}
// Seektime Update
function seektimeupdate(){
var nt = vid.currentTime * (100 / vid.duration);
seekslider.value = nt;
var curmins = Math.floor(vid.currentTime / 60);
var cursecs = Math.floor(vid.currentTime - curmins * 60);
var durmins = Math.floor(vid.duration / 60);
var dursecs = Math.floor(vid.duration - durmins * 60);
if(cursecs < 10){ cursecs = "0"+cursecs; }
if(dursecs < 10){ dursecs = "0"+dursecs; }
if(curmins < 10){ curmins = "0"+curmins; }
if(durmins < 10){ durmins = "0"+durmins; }
curtimetext.innerHTML = curmins+":"+cursecs;
durtimetext.innerHTML = durmins+":"+dursecs;
}
// Mute Function
function vidmute(){
if(vid.muted){
vid.muted = false;
mutebtn.innerHTML = "Mute";
} else {
vid.muted = true;
mutebtn.innerHTML = "Unmute";
}
}
// Set Volume Function
function setvolume(){ vid.volume = volumeslider.value / 100; }
// Full Screen Function
function toggleFullScreen(){
if(vid.requestFullScreen){
vid.requestFullScreen();
} else if(vid.webkitRequestFullScreen){
vid.webkitRequestFullScreen();
} else if(vid.mozRequestFullScreen){ vid.mozRequestFullScreen();
}
}
// ------------Add event listeners-----------------------------------------
var i;
for (i = 0; i < playbtn.length; i++) {
playbtn[i].addEventListener("click",playPause,false);
}
for (i = 0; i < seekslider.length; i++) {
seekslider[i].addEventListener("change",vidSeek,false);
}
for (i = 0; i < vid.length; i++) {
vid[i].addEventListener("timeupdate",seektimeupdate,false);
}
for (i = 0; i < seekslider.length; i++) {
mutebtn[i].addEventListener("click",vidmute,false);
}
for (i = 0; i < vid.length; i++) {
volumeslider[i].addEventListener("change",setvolume,false);
}
for (i = 0; i < seekslider.length; i++) {
fullscreenbtn[i].addEventListener("click",toggleFullScreen,false);
}
}
The Original JS:
//----------------------------Video Player--------------------------------------
var vid, playbtn, seekslider, curtimetext, durtimetext, mutebtn, volumeslider, fullscreenbtn;
//--------Functions------------------------------
// Initialize Player
function intializePlayer(){
window.onload = intializePlayer;
// Play/Pause Function
function playPause(){
if(vid.paused){
vid.play();
playbtn.style.background = "url(pause.png)";
} else { vid.pause();
playbtn.style.background = "url(play.png)";
}
}
// Video Seek Function
function vidSeek(){
var seekto = vid.duration * (seekslider.value / 100);
vid.currentTime = seekto;
}
// Seektime Update
function seektimeupdate(){
var nt = vid.currentTime * (100 / vid.duration);
seekslider.value = nt;
var curmins = Math.floor(vid.currentTime / 60);
var cursecs = Math.floor(vid.currentTime - curmins * 60);
var durmins = Math.floor(vid.duration / 60);
var dursecs = Math.floor(vid.duration - durmins * 60);
if(cursecs < 10){ cursecs = "0"+cursecs; }
if(dursecs < 10){ dursecs = "0"+dursecs; }
if(curmins < 10){ curmins = "0"+curmins; }
if(durmins < 10){ durmins = "0"+durmins; }
curtimetext.innerHTML = curmins+":"+cursecs;
durtimetext.innerHTML = durmins+":"+dursecs;
}
// Mute Function
function vidmute(){
if(vid.muted){
vid.muted = false;
mutebtn.innerHTML = "Mute";
} else {
vid.muted = true;
mutebtn.innerHTML = "Unmute";
}
}
// Set Volume Function
function setvolume(){ vid.volume = volumeslider.value / 100; }
// Full Screen Function
function toggleFullScreen(){
if(vid.requestFullScreen){
vid.requestFullScreen();
} else if(vid.webkitRequestFullScreen){
vid.webkitRequestFullScreen();
} else if(vid.mozRequestFullScreen){ vid.mozRequestFullScreen();
}
}
//----------------Set object references-------------------------------------
vid = document.getElementsByClassName("my_video");
playbtn = document.getElementsByClassName("playpausebtn");
seekslider = document.getElementsByClassName("seekslider");
curtimetext = document.getElementsByClassName("curtimetext");
durtimetext = document.getElementsByClassName("durtimetext");
mutebtn = document.getElementsByClassName("mutebtn");
volumeslider = document.getElementsByClassName("volumeslider");
fullscreenbtn = document.getElementsByClassName("fullscreenbtn");
// ------------Add event listeners-----------------------------------------
playbtn.addEventListener("click",playPause,false);
seekslider.addEventListener("change",vidSeek,false);
vid.addEventListener("timeupdate",seektimeupdate,false);
mutebtn.addEventListener("click",vidmute,false);
volumeslider.addEventListener("change",setvolume,false);
fullscreenbtn.addEventListener("click",toggleFullScreen,false);
}
The HTML:
<div id="evid">
<video class="videogunshots" width="550" height="300">
<source src="file:///C|/Users/Godsnake/Desktop/July14/content/gunshots.mp4" type="video/mp4">
<source src="file:///C|/Users/Godsnake/Desktop/July14/content/gunshots.webm" type="video/webm">
<source src="file:///C|/Users/Godsnake/Desktop/July14/content/gunshots.ogg" type="video/ogg">
</video>
<div class="videocontrols">
<button class="playpausebtn" onclick="playPause()">Play</button>
<input class="seekslider" type="range" min="0" max="100" value="0" step="1">
<span class="curtimetext">00:00</span> / <span class="durtimetext">00:00</span>
<button class="mutebtn">Mute</button>
<input class="volumeslider" type="range" min="0" max="100" value="100" step="1">
<button class="fullscreenbtn">[ ]</button>
</div>
</div>
On a different note the video I"m playing doesnt seem to fit the container with Object-fit:fill any idea why?
document.getElementsByClassName returns a collection of elements rather than just a single element. In order to attach an event listener, you will need to loop through each one and attach individually.
Something like this:
var i;
for (i = 0; i < playbtn.length; i++) {
playbtn[i].addEventListener("click",playPause,false);
}
for (i = 0; i < seekslider.length; i++) {
seekslider[i].addEventListener("change",vidSeek,false);
}
...
Update:
I just took a look at your JSFiddle. You're calling local resources (things on your computer) that cannot be accessed on the web. The buttons, even the file itself, need to live on a server where they can be accessed. Until that happens, none of this will work.
One of the biggest things that helped me when I was learning was figuring out how to use the console in Chrome Developer Tools (Firefox has a good set of tools as well). Any errors will get spat out there.

Adding start, stop, and reset buttons for a timer

I'm making a timer and have it working already one load. I want to add a start, stop, and reset button to it. This is my code as is atm.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'),
minutesLabel = document.getElementById('minutes'),
hoursLabel = document.getElementById('hours'),
totalSeconds = 0,
startButton = document.getElementById('start'),
resetButton = document.getElementById('reset'),
onOff = 0;
startButton.onclick = function() {
onOff = 1;
};
resetButton.onclick = function() {
totalSeconds = 0;
onOff = 0;
};
if ( onOff == 1 ) {
setInterval( setTime, 1000 );
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad( totalSeconds % 60 );
minutesLabel.innerHTML = pad( parseInt( totalSeconds / 60 ) );
hoursLabel.innerHTML = pad( parseInt( totalSeconds / 3600 ) )
}
function pad( val ) {
var valString = val + "";
if( valString.length < 2 ) {
return "0" + valString;
} else {
return valString;
}
}
}
})();
The buttons are not working atm however. I'm not sure if this the best solution for the goal as well, so suggestions are welcome.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'), minutesLabel = document.getElementById('minutes'), hoursLabel = document
.getElementById('hours'), totalSeconds = 0, startButton = document.getElementById('start'), stopButton = document.getElementById('stop'), resetButton = document
.getElementById('reset'), timer = null;
startButton.onclick = function() {
if (!timer) {
timer = setInterval(setTime, 1000);
}
};
stopButton.onclick = function() {
if (timer) {
clearInterval(timer);
timer = null;
}
};
resetButton.onclick = function() {
if (timer) {
totalSeconds = 0;
stop();
}
};
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
hoursLabel.innerHTML = pad(parseInt(totalSeconds / 3600))
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
})();
<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
</form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting. Click on the "Start count!" button to start the timer again.
</p>
</body>
</html>

Categories