I am trying to set the position of an audio source to the remainder of the time since the UNIX epoch divided by the duration of the audio in milliseconds. audio0.duration
and the other two return a value of NaN
. How can I get the audio duration to be an integer that I can use?
JavaScript code is below.
function PlaySample (file) {
const audio0 = new Audio('https://brysonnoble.github.io/Programming%20Projects/SmartSync/Sample_Audio/a0.mp3');
const audio1 = new Audio('https://brysonnoble.github.io/Programming%20Projects/SmartSync/Sample_Audio/a1.mp3');
const audio2 = new Audio('https://brysonnoble.github.io/Programming%20Projects/SmartSync/Sample_Audio/a2.mp3');
audio0.pause();
audio1.pause();
audio2.pause();
switch (file) {
case 0:
audio0.currentTime = PlayheadPos(audio0.duration * 1000);
audio0.play();
break;
case 1:
audio1.currentTime = PlayheadPos(audio1.duration * 1000);
audio1.play();
break;
case 2:
audio2.currentTime = PlayheadPos(audio2.duration * 1000);
audio2.play();
break;
default:
break;
}
}
function PlayheadPos (audioLen) {
alert(Date.now() % audioLen);
return Date.now() % audioLen;
}
2
Answers
That happens because the
duration
property of the audio/media isundefined
. Try enabling theplay
function when the eventdurationchanges
is fired in the audio/media element.I created this snippet for you that can help you solve your problem.
This snippet is fully working and plays at least the last 10% of the audio or the result of your custom expression.
I did this because the result of your custom expression sometimes result in a time that is greater than the duration of the audio and it will not play at all.
NOTE: The buttons will only be enabled when there’s a duration for that audio.
I hope this helps you. But you’ll have to adjust it though…
JavaScript math is at times inaccurate because it stores numbers in memory as binary floats, for details see Why JavaScript is Bad At Math. When converting sec to ms the calculations end up to be roughly a little under a minute over
duration
so when that invalid value was assigned tocurrentTime
theAudio
object wouldn’t play (as user2804429 explained). In the example below, the huge number that isDate.now()
is more manageable as seconds. As of this writing the expression:(Date.now() / 1000) % duration
🞷 is always less thanduration
.I liked user2804429’s solution to disable the UI until the mp3 was ready so I added my own version of that idea to the example below (
<button>
s are enabled when"canplay"
event fires). Details are commented in the example.🞷 I increased the range of random times by dividing the EPOCH by 100 insead of 1000.
See comments in
randomPos()
of the example.