简体   繁体   中英

Getting the duration of an MP3 file with JavaScript using “Web Audio API” and “AudioContext”

Is there any way to get the duration of an MP3 file with JavaScript using Web Audio API and AudioContext ?

I can get that duration with the HTML5 element: <audio/> but I want to use the Web Audio API .

Below is the code I have so far. If you have any suggestion, please, fork my code on: CodePen.io and post the link.

CodePen.io code: https://codepen.io/anon/pen/QZwyqd

 window.addEventListener('load', () => { const URL = 'https://www.tophtml.com/snl/15.mp3'; let url = URL + '?nocache='+(new Date()).getTime(); let audio = document.querySelector('audio'); audio.setAttribute('src', url); audio.addEventListener('durationchange', function() { log('way 1: ' + this.duration); }); getAudioDurationWithAudioContext().then((duration) => { log('way 2: ' + duration); }); log('...'); }); function getAudioDurationWithAudioContext() { // PLEASE, IMPLEMENT THIS FUNCTION AND "FORK" THIS CODE return new Promise((resolve, reject) => { setTimeout(() => { resolve('???.???'); }, 1000); }); } function log(text, append = true) { let logger = document.querySelector('.logger'); if (text == '') { logger.innerHTML = ''; return; } if (!append) logger.innerHTML = ''; let entry = document.createElement('div'); entry.innerHTML = text; logger.appendChild(entry); } 
 .logger { display: inline-block; font-family: monospace; white-space: pre; font-size: 13px; margin-top: 10px; background-color: #d4e4ff; } .logger { padding: 4px; } .divider { border-top: 1px solid #ccc; margin: 10px 0; } 
 <div> <audio controls preload="auto"></audio> </div> <div class="logger"></div> 

Thanks!

Once you've got your AudioBuffer it has a duration property. This is a double representing the duration in seconds.

Yes, it's possible to do this and without an audio tag. You need to download audio file using Ajax/XMLHttpRequest and decode the file like this:

// Step 1: We need AudioContext instance to decode audio files.
var context = new AudioContext();


// Step 2: Download a .mp3 file using AJAX
var request = new XMLHttpRequest();
request.addEventListener('load', fileLoaded);
request.open('GET', 'https://www.tophtml.com/snl/15.mp3');
request.responseType = 'arraybuffer';
request.send();


// Step 3: File downloaded, need to be decoded now.
function fileLoaded() {
    if (request.status < 400)
        context.decodeAudioData(request.response, fileDecoded);
}


// Step 4: File decoded, we can get the duration.
function fileDecoded(audioBuffer) {

    // This is the duration you want, in seconds:
    audioBuffer.duration;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM