parisian
parisian

Reputation: 41

Get audio duration in JS and display in HTML

I have the following code running fine in order to display an audio player but I would like to also get the total duration of the audio file to be displayed :

HTML

    <button id="playAudio"></button>

    <div id="seekObjContainer">
        <div id="seekObj">
            <div id="percentage"></div>
        </div>
    </div>

    <p><small id="currentTime">00:00</small></p>

</div>

JS

    // Audio Player

function $(id) { return document.getElementById(id); };
const media = document.getElementById('audio');

let ui = {
    play: 'playAudio',
    audio: 'audio',
    percentage: 'percentage',
    seekObj: 'seekObj',
    currentTime: 'currentTime'
};

function togglePlay() {
    if (media.paused === false) {
        media.pause();
        $(ui.play).classList.remove('pause');
    } else {
        media.play();
        $(ui.play).classList.add('pause');
    }
}

function calculatePercentPlayed() {
    let percentage = (media.currentTime / media.duration).toFixed(2) * 100;
    $(ui.percentage).style.width = `${percentage}%`;
}

function calculateCurrentValue(currentTime) {
    const currentMinute = parseInt(currentTime / 60) % 60;
    const currentSecondsLong = currentTime % 60;
    const currentSeconds = currentSecondsLong.toFixed();
    const currentTimeFormatted = `${currentMinute < 10 ? `0${currentMinute}` : currentMinute}:${currentSeconds < 10 ? `0${currentSeconds}` : currentSeconds
        }`;

    return currentTimeFormatted;
}

function initProgressBar() {
    const currentTime = calculateCurrentValue(media.currentTime);
    $(ui.currentTime).innerHTML = currentTime;
    $(ui.seekObj).addEventListener('click', seek);

    media.onended = () => {
        $(ui.play).classList.remove('pause');
        $(ui.percentage).style.width = 0;
        $(ui.currentTime).innerHTML = '00:00';
    };

    function seek(e) {
        const percent = e.offsetX / this.offsetWidth;
        media.currentTime = percent * media.duration;
    }

    calculatePercentPlayed();
}

$(ui.play).addEventListener('click', togglePlay)
$(ui.audio).addEventListener('timeupdate', initProgressBar);

What I would like :

I would like to get in html the total duration of the audio file in order to get currentime / duration displayed. Any idea?

Upvotes: 1

Views: 3578

Answers (1)

Ofir Baruch
Ofir Baruch

Reputation: 10356

According to MDN: (https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/duration)

myDuration = htmlMediaElement.duration

A double-precision floating-point value indicating the duration of the media in seconds. If no media data is available, the value NaN is returned. If the element's media doesn't have a known duration—such as for live media streams—the value of duration is +Infinity.

However, you'll need to make sure that the audio (its metadata to be precise) has been loaded before trying to access that property - using the onloadedmetadata event.

So, first - add a DIV in your html code.

And then add the js code:

media.onloadedmetadata = function() {
  document.getElementById('total-duration').innerText = media.duration;
};

Upvotes: 1

Related Questions