0

I am using vanilla JS, webaudioAPI and canvas elements to create an audio visualizer.

When I update the audio element src with javascript, I need the audio element duration property to update two variables for my spectrogram visualizers. I want to use the duration property right after changing the src with javascript, but it returns NAN within the function.

Here is the code:

async function chooseTrack(trackTxt) {
  audioElem.src = `tracks/${trackTxt}`;
  await audioElem.load()
}

async function updateAudioContext(trackTxt) {
  await audioCtx.suspend()
  .then(() =>  chooseTrack(trackTxt))
  .then(() => {
      console.log(audioElem)
      console.log(audioElem.duration)
      frameLength = 360 / ((audioElem.duration * 1000)/ 3.2) ; 
      freqHeight = 250 / bufferLength;

  })
}


I can make it work with setTimeOut, but I would like a more elegant solution to access this property of the new source file within the function calls. This works:

setTimeout(() => {
      console.log(audioElem)
      console.log(audioElem.duration)
      frameLength = 360 / ((audioElem.duration * 1000)/ 3.2) ; /
      freqHeight = 250 / bufferLength;
    }, 50)

I'd rather not use setTimeOut to wait for the updated duration property in the function. What am I doing wrong?

8
  • the HTMLMediaElement load() method does not return a Promise - you'll need to create a Promise that resolves when the loadeddata or loadedmetadata or canplay Event fires Commented Sep 29, 2024 at 4:49
  • maybe this code helps? Commented Sep 29, 2024 at 4:57
  • ok thanks i'll try that. I also thought that calling chooseTrack() within .then(), even without a promise, would finish before the next .then() but I guess it doesn't wait. Commented Sep 29, 2024 at 4:57
  • @JaromandaX, it could be achieved by using audioElem.addEventListener('load', onLoadFn)... Commented Sep 29, 2024 at 4:58
  • @user2804429 - yeah, wasn't sure if <audio> elements would fire load when manipulating the source through HTMLMediaElement ...edit: <audio> elements NEVER fire load, according to documentation, so, no, that wouldn't work Commented Sep 29, 2024 at 4:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.