Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

435
Views
How to get duration globally from audio file in javascript when using Audiocontext() API?

I used AudioContext API to get duration from audio answered to stackoverflow as follows:

let durationTime;

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

// Step 2: Download a .mp3 file using AJAX
let request = new XMLHttpRequest();
request.addEventListener('load', fileLoaded);
request.open('GET', '/sounds/2W.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);
        console.log(`durationTime at fileLoaded : ${durationTime}`)
}


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

    // This is the duration you want, in seconds:
    durationTime = audioBuffer.duration;
    console.log(`durationTime at fileDecoded : ${durationTime}`)
}

console.log(`durationTime at global = ${durationTime}`)

The result of this code as follows:

durationTime at global = 0

durationTime at fileLoaded : 0

durationTime at fileDecoded : 1.1363125

It works within function fileDecoded(audioBuffer) as a local variable, but the variable of durationTime doesn't works at globally. Why and how can I use this variable of durationTime as globally ?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!