Any way to get a currentTime value prior to the seek on HTMLMediaElement? - javascript

Let's say our app is using the default video player on Safari.
When a user is playing a video and then attempts to move to a different position of the video using the seek bar, it seems like pause event is fired first, and then we'll get seeking and seeked events fired.
I am wondering if we can get the currentTime value prior to the seek. For instance, assuming that a user jumps from t = 7 to t = 42 using the seek bar, I want to get 7 as the currentTime value somehow.
I expected that we could get this value by accessing currentTime property inside the pause event handler that is invoked right after the seek like the following:
const video = document.querySelector('#myvideo');
video.addEventListener('pause', () => {
// I expected that the `video.currentTime` here has the "previous" position,
// but it already points to the new position
console.log(video.currentTime);
});
but unfortunately the currentValue was already updated to the new value at that point.
Is there any good way to achieve it?
(EDIT)
Caching currentTime manually doesn't help, because apparently a timeupdate event fires before a pause event. More specifically, taking the following code as an example, when a user attempts to jump to another position, cache and currentTime printed within the pause handler seem always identical.
<!DOCTYPE html>
<html>
<body>
<video
id="myvideo"
width="640"
height="360"
controls
src="video.mp4"
></video>
</body>
<script>
const video = document.querySelector("#myvideo");
let cache = 0;
video.addEventListener("timeupdate", () => {
cache = video.currentTime;
});
video.addEventListener("pause", () => {
console.log({ cache, currentTime: video.currentTime });
});
</script>
</html>

I think #Kaiido means this when saying "Cache two values".
Code is untested (but looks better than being kept in comments section)
<script>
const video = document.querySelector("#myvideo");
let cache = 0;
let cache_prev = 0;
video.addEventListener("timeupdate", () => {
cache_prev = cache; //# save last known value
cache = video.currentTime; //# before updating to new currentTime
});
video.addEventListener("pause", () => {
console.log("cache_prev : " + cache_prev );
console.log("cache : " + cache );
console.log("currentTime : " + video.currentTime );
});
</script>

Related

How to get duration from audio tag in react? [duplicate]

I have a html5 <audio> tag in page, but how can I know its duration time?
<audio controls="">
<source src="p4.2.mp3">
</audio>
2020 solution:
You will get undefined or NaN (not a number) when the audio metadata isn't loaded yet. Therefore some people suggested to use onloadedmetadata to make sure the metadata of the audio file is fetched first. Also, what most people didn't mention is that you have to target the first index of the audio DOM element with [0] like this:
-- Vanilla Javascript:
var audio = document.getElementById('audio-1');
audio.onloadedmetadata = function() {
alert(audio.duration);
};
If this won't work try this, however not so reliable and dependent on users connection:
setTimeout(function () {
var audio = document.getElementById('audio-1');
console.log("audio", audio.duration);
}, 100);
-- JQuery:
$(document).ready(function() {
var audio = $("#audio-1")[0];
$("#audio-1").on("loadedmetadata", function() {
alert(audio.duration);
});
});
var au = document.createElement('audio');
au.addEventListener('loadedmetadata',function(){
au.setAttribute('data-time',au.duration);
},false);
In a comment above, it was mentioned that the solution is to bind an event handle to the event loadedmetadata. This is how I did that -
audio.onloadedmetadata = function() {
alert(audio.duration);
};
I was struggling with loading the duration in a React component so following #AlexioVay's solution, here is an answer if you're using React:
This assumes you are using a ref for your audio component class which you will need to target the audio elements for your play/pause handler(s).
<audio /> element:
<audio ref={audio => { this.audio = audio }} src={this.props.src} preload="auto" />
Then in your componentDidMount():
componentDidMount() {
const audio = this.audio
audio.onloadedmetadata = () => {
console.log(audio.duration)
this.setState({
duration: this.formatTime(audio.duration.toFixed(0))
})
}
}
And finally the formatTime() function:
formatTime(seconds) {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
const s = seconds % 60
return [h, m > 9 ? m : h ? '0' + m : m || '0', s > 9 ? s : '0' + s]
.filter(a => a)
.join(':')
}
With this, the duration in h:mm:ss format will display as soon as the audio src data is loaded. Sweetness.
I used "canplaythrough" event to get the track duration. I have a case where I have two players, and I want to stop the second player 2 seconds before the first one is complete.
$('#' + _currentPlayerID).on("canplaythrough", function (e) {
var seconds = e.currentTarget.duration;
var trackmills = seconds * 1000;
var subTimeout = trackmills - 2000; //2 seconds before end
//console.log('seconds ' + seconds);
//console.log('trackmills ' + trackmills);
//console.log('subTimeout ' + subTimeout);
//Stop playing before the end of thet track
//clear this event in the Pause Event
_player2TimeoutEvent = setTimeout(function () { pausePlayer2(); }, subTimeout);
});
Simply use audioElement.duration
To obtain the end of reading it is necessary that 'loop = false' with the event 'onended'. If loop = true, onended does not work;)
To make a playlist, you have to set loop = false to use the 'onended' event in order to play the next song.
for the duration if your script is done correctly you can recover the duration anywhere. If the value of 'duration' is NaN the file is not found by the browser. If the value is 'Infinity' 'INF' it is a streaming, in this case, adds 1 mn compared to the reading time 'currentime'.
For * I.E it's crap. Currenttime may be greater than duration, in which case you do:
var duration = (this.currentime> this.duration)? this.currenttime: this.duration;
That's (O_ °)
it's better to use the event like this ...
ObjectAudio.onprogress =function(){
if(this.buffered.length){
var itimeend = (this.buffered.length>1)? this.buffered.end(this.buffered.length-1):this.buffered.end(0);
....
Your code here.......
}
}

Using 'this.currentTime' to get the time of a video and reset it to the starting point on 'hover out'

I have a video library where I want to dynamically use the Media Fragment time in URL as the poster.
When hovering out, I am trying to reset the video to the initial start - to make sure the poster is at 2 seconds (in this specific example) instead of 0.
this.load works but creates a bad user experience as the whole video loads in again.
My idea is to define the current time as a variable (before the video starts playing) and use it when pausing the video.
However I just get "Uncaught ReferenceError: posterTime is not defined".
<video id="video">
<source src="videourl.mp4#t=2" type="video/mp4">
</video>
const videos = document.querySelectorAll("video")
videos.forEach(video => {
video.addEventListener("mouseover", function () {
var posterTime = this.currentTime;
this.currentTime = 0;
this.play()
})
video.addEventListener("mouseout", function () {
this.currentTime = posterTime;
this.pause();
})
})
Note that I use Webflow and is not very strong with jQuery/Javascript.
My idea is to define the current time as a variable (before the video
starts playing) and use it when pausing the video. However I just get
"Uncaught ReferenceError: posterTime is not defined".
Your idea and code is fine but you made a basic mistake.
Remember: A variable defined inside a function will exist only for that function where it was created.
Use let for internal variables (where possible) and use var for global variables.
solution: Define the variable as global (outside of any functions)...
const videos = document.querySelectorAll("video");
var posterTime = -1; //# global var, with starting value...
videos.forEach(video => {
video.addEventListener("mouseover", function ()
{
posterTime = this.currentTime; //# set time
this.currentTime = 0;
this.play()
})
video.addEventListener("mouseout", function ()
{
this.currentTime = posterTime; //# get time
this.pause();
})
})
As I hover out I need it to show that initial frame again (not the first frame, but the one set in the URL)
Given this requirement you can retrieve the fragment from the URL in the src attribute of the source element and apply it to the currentTime of the video when the mouseleave event occurs:
const videos = document.querySelectorAll("video")
videos.forEach(video => {
video.addEventListener("mouseenter", function() {
this.currentTime = 0;
this.play()
})
video.addEventListener("mouseleave", function() {
let src = this.querySelector('source').src;
let time = (src.split('#')[1] || 't=0').split('=')[1];
this.currentTime = time;
this.pause();
})
})
<video id="video">
<source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4#t=5" type="video/mp4">
</video>

How to make a short beep in javascript that can be called *repeatedly* on a page?

This is like the question at:
Sound effects in JavaScript / HTML5
but I'm just seeking a specific answer to the issue of repeatability.
The above question and other similar ones have helpful answers to use the following javascript:
function beep1()
{ var snd = new Audio("file.wav"); // buffers automatically when created
snd.play();
}
or even more self-contained, you can now include a wav in-line, such as:
function beep2()
{ var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4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5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
snd.play();
}
When I tried these examples, I could only get the sound to play once on my computer. I noticed this was a common complaint in multiple questions, but never saw an answer to it.
The closest thing to an answer was in the referenced question in which #Kornel stated:
To play same sound multiple times, create multiple instances of the Audio object.
You could also set snd.currentTime=0 on the object after it finishes playing.
If this is the key to my puzzle, I don't quite understand it. (I don't know how to destroy / release an audio object.) Can someone show me exactly how to get a button to keep replaying my sound every time it is clicked, either using one of the suggestions of #Kornel or some other way?
Put the sound references outside of the function. Otherwise, each time you call the function, a new sound object is created.
var snd1 = new Audio("file.mp3");
var snd2 = new Audio("data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU1LjEyLjEwMAAAAAAAAAAAAAAA//uQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAAcAAAAIAAAOsAA4ODg4ODg4ODg4ODhVVVVVVVVVVVVVVVVxcXFxcXFxcXFxcXFxjo6Ojo6Ojo6Ojo6OqqqqqqqqqqqqqqqqqsfHx8fHx8fHx8fHx+Pj4+Pj4+Pj4+Pj4+P///////////////9MYXZmNTUuMTIuMTAwAAAAAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//uQRAAAAn4Tv4UlIABEwirzpKQADP4RahmJAAGltC3DIxAAFDiMVk6QoFERQGCTCMA4AwLOADAtYEAMBhy4rBAwIwDhtoKAgwoxw/DEQOB8u8McQO/1Agr/5SCDv////xAGBOHz4IHAfBwEAQicEAQBAEAAACqG6IAQBAEAwSIEaNHOiAUCgkJ0aOc/a6MUCgEAQDBJAuCAIQ/5cEAQOCcHAx1g+D9YPyjvK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X9v7/X8y1f/////////49WAzMzEYYMZLq6CUANIqbDX7lisBIdraAEPwShTRc9WZ2vAqBc4NQ9GrUNaw0Czcrte0g1NEoiU8NFjx4NFh54FSwlOlgaCp0S3hqo8SLOh3/63f7P/KgKJxxhgGSnAFMCnIogwU5JoqBIDAuBIiNLETyFmiImtYiDTSlb8ziIFYSFv/QPC38zyxEOuPeVGHQ77r/1u/+kq49//6g4gjoVQSUMYQUSAP8PwRcZIyh2kCI2OwkZICZmaZxgnsNY8DmSCWX0idhtz3VTJSqErTSB//1X7TTTVVV//uSZB2P8xwRJ4HvYcItQlWBACM4AAABpAAAACAAADSAAAAEVf/+qCE000VVVVU0002//+qqqqummmmr///qqqppppoqqqqppppoqqATkEjIyIxBlBA5KwUEDBBwkFhYWFhUVFfiqhYWFhcVFRUVFv/Ff/xUVFRYWFpMQU1FMy45OS41qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqg==");
function beep1() {
snd1.play();
}
function beep2() {
snd2.play();
}
beep1();
setInterval(beep2, 300);
We can create audio waveforms with the web audio api.
The following example shows a bip, made of two tones, one is at 233hz for 100ms with a gain of 10DB, the second is at 603Hz with a duration of 200ms, with 3DB of gain.
Both sounds are in a loop of 1500ms, with the help of setInterval.
This is a minimal example, it can't be stopped! (As asked!)
// gain, frequency, duration
let a = new AudioContext()
function k(w,x,y){
console.log("Gain:"+w, "Hz:"+x, "ms:"+y)
v = a.createOscillator()
u = a.createGain()
v.connect(u)
v.frequency.value = x
v.type = "square"
u.connect(a.destination)
u.gain.value = w * 0.01
v.start(a.currentTime)
v.stop(a.currentTime + y *0.001)
}
setInterval(function(){ k(10,233,100); k(3,603,200)}, 1500)
There is ways to create much more complex 8bits songs in few lines, with differents loops of many duration and tones:
let a = new AudioContext()
function k(w,x,y){
console.log("Gain:"+w, "Hz:"+x, "ms:"+y)
let v = a.createOscillator()
let u = a.createGain()
v.connect(u)
v.frequency.value = x
v.type = "square"
u.connect(a.destination)
u.gain.value = w * 0.01
v.start(a.currentTime)
v.stop(a.currentTime + y *0.001)
}
setInterval(function(){ k(10,233,100); k(3,603,200)}, 1000)
setInterval(function(){ k(8,1646,100); k(8,1444,100) }, 500)
setInterval(function(){ k(8,728,100); k(8,728,100) }, 3000)
setInterval(function(){ k(8,728,100); k(8,728,100) }, 3000)
setInterval(function(){ k(8,364,100); k(8,364,100) }, 6000)
setInterval(function(){ k(8,364,100); k(8,157,200) }, 12000)
We can as well set the values in an array, and loop trough it.
With for, for..in, while, do..while, much more complex, but to create patterns, arpeggios, etc.
Someone, one day will enjoy this ;)
What about using the new Audio API. (No Microsoft support!)
var audioContext = AudioContext && new AudioContext();
function beep(amp, freq, ms){//amp:0..100, freq in Hz, ms
if (!audioContext) return;
var osc = audioContext.createOscillator();
var gain = audioContext.createGain();
osc.connect(gain);
osc.value = freq;
gain.connect(audioContext.destination);
gain.gain.value = amp/100;
osc.start(audioContext.currentTime);
osc.stop(audioContext.currentTime+ms/1000);
}
Didn't you try this
Just the HTML5 thing
<audio controls loop>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
I needed an "alert" for a web app that will be used predominately on a mobile device. The new autoplay policy https://developers.google.com/web/updates/2017/09/autoplay-policy-changes, was giving me a problem so I did this...
Top of html code to play the "alert" you need a button so the user interacts with the page and authorizes future use of audio.
<p align="center" id="snd_btn"><button id="allow_alert" class="btn btn-danger" onclick="play_sound();"> Allow Alert </button></p>
Add'l html...................
then later in the script section I have ....
<script>
function play_sound(){
snd.play(); // plays the "1-second-of-silence.mp3"
$("#snd_btn").hide(); // this hides the prompt "Allow Alert"
}
snd = new Audio("sound/1-second-of-silence.mp3");
snd2 = new Audio("sound/PHONERNG.WAV");
the as part of an online event (map coordinates update) this is included in the ajax success function ...
success: function(data){
if(data['badge'] > 0){
$("#vt_badge").html(data['badge']);
snd2.play(); //Plays the "alert" sound
}
}
'''''
</script>
Th "allow alert" button is only there on page load so the user interacts with it, and it plays a sound, "1-second-of-silence.mp3". That satisfies the player's requirement for page interaction, now the actual alert, "PHONERNG.WAV" plays automatically as required.
MrFitz
This works better for me.
Just follow the snippet below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Press the Button</h1>
<button onclick="play()">Press Here!</button>
<script>
function play() {
var audio = new Audio(
'https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3');
audio.play();
}
</script>
</body>
</html>

Black screen when changing HTML5 video src

I'm trying to change video source with javascript and set the currentTime to the time when the src changed but I get a black screen on Chrome and a freezing screen in Firefox with a weird sound like when I change src. If I remove
$("#video").on("canplay",function(){
video.currentTime = time;
});
it works fine.
<video src="http://srv35.clipconverter.cc/download/tdCQhWZj2IqwZGpolpWUaXFk5KWmqWxt4pSXaWlmnGhkZnK0qc%2FMqHyf1qiZpa2d2A%3D%3D/Blunt%20%26%20Real%20ft.%20Ledri%20Vula%20-%20Nese%20m%27don%20ti%20-%20Remix%20%28Official%20Video%20HD%29.mp4" id="video" autoplay></video>
<div id="360p" class="quality">360p</div>
var video = document.getElementById('video');
var time;
var _360p = "http://r3---sn-p5qlsnel.googlevideo.com/videoplayback?ratebypass=yes&sparams=id,initcwndbps,ip,ipbits,itag,mime,mm,ms,mv,ratebypass,source,upn,expire&ipbits=0&mt=1410631565&sver=3&itag=18&expire=1410653286&mm=31&upn=vTh5FN82i_U&id=o-AJXkFxYoWM1bFEPoTrX53eNVZbgtwutGGXv655WRWj4Q&mime=video/mp4&initcwndbps=1202000&ip=2001:41d0:2:40c5:a8b1:cb97:ef0b:b1b4&key=yt5&fexp=900147,927622,931983,932404,934030,936117,945539,946023,947209,952302,953801&source=youtube&mv=m&ms=au&signature=A77C56E95778206A0A06799B860CECFAE8A35ED8.C27AA1B748D371DFCC52DA1219133F63FDBDABB4&&title=Blunt+%26+Real+ft.+Ledri+Vula+-+Nese+m%27don+ti+-+Remix+%28Official+Video+HD%29";
var _1080p = "http://srv35.clipconverter.cc/download/tdCQhWZj2IqwZGpolpWUaXFk5KWmqWxt4pSXaWlmnGhkZnK0qc%2FMqHyf1qiZpa2d2A%3D%3D/Blunt%20%26%20Real%20ft.%20Ledri%20Vula%20-%20Nese%20m%27don%20ti%20-%20Remix%20%28Official%20Video%20HD%29.mp4";
video.addEventListener("timeupdate", function() {
time = video.currentTime;
});
$("#360p").click(function() {
$("#preload").attr("src", _360p)
$("#preload").on("canplay",function(){
$('#video').attr("src", _360p);
$("#video").on("canplay",function(){
video.currentTime = time;
});
});
});
http://jsfiddle.net/cc88530p/7/
Setting video.src and video.currentTime are likely to result in calls to the timeupdate and canplay handlers. I think you want to unregister the timeupdate handler before setting video.src, and probably unregister the video.oncanplay handler before setting video.currentTime. (I can't test this in your jsfiddle because the googlevideo URL returns 403 Forbidden.)

Custom progress bar for <audio> and <progress> HTML5 elements

I am mind boggled at working out how to create a custom seekbar for an audio player using the tag and simple Javascript.
Current Code:
<script>
function play() {
document.getElementById('player').play();
}
function pause() {
document.getElementById('player').pause();
}
</script>
<audio src="sample.mp3" id="player"></audio>
<button onClick="javascript:play()" >Play</button>
<button onClick="javascript:pause()" >Pause</button>
<progress id="seekbar"></progress>
Would it be possible to link the progress bar so that when i play a song the progress is shown?
Yes, it is possible using the timeupdate event of the audio tag. You receive this event every time the position of the playback is updated. Then, you can update your progress bar using the currentTime and duration properties of the audio element.
You can see a working example in this fiddle
If you want smooth progress bar,try somethink like that
HTML:
<div class="hp_slide">
<div class="hp_range"></div>
</div>
CSS:
.hp_slide{
width:100%;
background:white;
height:25px;
}
.hp_range{
width:0;
background:black;
height:25px;
}
JS:
var player = document.getElementById('player');
player.addEventListener("timeupdate", function() {
var currentTime = player.currentTime;
var duration = player.duration;
$('.hp_range').stop(true,true).animate({'width':(currentTime +.25)/duration*100+'%'},250,'linear');
});
Pretty rough,but works
Here's a simple vanilla example:
const url = "https://upload.wikimedia.org/wikipedia/en/a/a9/Webern_-_Sehr_langsam.ogg";
const audio = new Audio(url);
const playBtn = document.querySelector("button");
const progressEl = document.querySelector('input[type="range"]');
let mouseDownOnSlider = false;
audio.addEventListener("loadeddata", () => {
progressEl.value = 0;
});
audio.addEventListener("timeupdate", () => {
if (!mouseDownOnSlider) {
progressEl.value = audio.currentTime / audio.duration * 100;
}
});
audio.addEventListener("ended", () => {
playBtn.textContent = "▶️";
});
playBtn.addEventListener("click", () => {
audio.paused ? audio.play() : audio.pause();
playBtn.textContent = audio.paused ? "▶️" : "⏸️";
});
progressEl.addEventListener("change", () => {
const pct = progressEl.value / 100;
audio.currentTime = (audio.duration || 0) * pct;
});
progressEl.addEventListener("mousedown", () => {
mouseDownOnSlider = true;
});
progressEl.addEventListener("mouseup", () => {
mouseDownOnSlider = false;
});
button {
font-size: 1.5em;
}
<button>▶️</button>
<input type="range" value="0" min="0" max="100" step="1">
The approach is to use an input[type="range"] slider to reflect the progress and allow the user to seek through the track. When the range changes, set the audio.currentTime attribute, using the slider as a percent (you could also adjust the max attribute of the slider to match the audio.duration).
In the other direction, I update the slider's progress on timeupdate event firing.
One corner case is that if the user scrolls around with their mouse down on the slider, the timeupdate event will keep firing, causing the progress to hop around between wherever the user's cursor is hovering and the current audio progress. I use a boolean and the mousedown/mouseup events on the slider to prevent this from happening.
See also JavaScript - HTML5 Audio / custom player's seekbar and current time for an extension of this code that displays the time.
First of all, don't use the progress element, it's a shitty element (for now) and styling it is a huge pain in... well it's boring (look at a little project I made, look at it (and it's juste webkit/moz)).
Anyway, you should read the doc on MDN, it's very easy and with a lot of examples. What you are looking for is the currentTime attribute, here a little snippet :
var audio = document.querySelector('#player')
audio.currentTime = 60 // will go to the 60th second
So what you need is to use the cross-multiplication (div is the element you use as a progress bar) :
Where I clicked on div | THE TIME I WANT TO KNOW
————————————————————————————————————————
Total length of div | The total time of my video/audio (audio.seekable.end())

Categories

Resources