gbabyblue
gbabyblue

Reputation: 1

How to wait for media element source to actually update with Async/Await?

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?

Upvotes: 0

Views: 47

Answers (0)

Related Questions