0

So.. I'm developing an web app.. basically i need to ask my backend for an mp3 through a get request (can't be cached as that is updated frequently, in fact this code is part of an uploader component to change that) and then i need to loop that indefinitely.

If you try to loop with the HTML Audio element it doesn't loop seamlessy.. so i found some code that basically creates two HTML Audio components and takes care of looping it seemlessly by playing them simultanously and juggling between the volume of the two...

It works perfectly, BUT, i wanna optimize this thing... Currently I'm asking the backend for the same file three times... once for a buffer Audio component (i only need the duration off this, as it can't be saved on the backend currently) and two times for each HTMLAudio inside the SeamlessLoop code i found.

This problem is even accentuated by the fact i have 5 of those loops that i need to load every time.

//I removed part of the code to make it more digestable

loadAudio() {
  for (let i = 1; i <= 5; i++) {
    let url = this.audio.tracks[i]

    let audio = new Audio()
    audio.src = url
    audio.load
    audio.addEventListener('loadedmetadata', () => {
      this.loops[`lvl${i}`] = new SeamlessLoop()

      //SeamlessLoop.addUri is basically how you inizialize this class
      //inside it creates two Audio elements and everything else it needs
      //addUri(src: string, duration: number, name: string)
      this.loops[`lvl${i}`].addUri(url, audio.duration*1000, 'loop')
    })
  }
}

Now, i have a bunch of solutions already..

  • I could store the duration of the file whenever it's changed on the db so i could only download the file once (setting the cache to 5 seconds or something on the backend)
  • Alternatively I could cache the files from the backend to a regular time and just change the file name every time a new one is uploaded

I would prefer to avoid both solution as both would require some restructuring of the backend that might not be worth it...

Therefore here's my question:

Is there a way to force an url to be loaded from cache by the browser? Kind of like adding a # after an url to force it to download it fresh insteal of pulling from cache but the opposite... If that's a thing, It would solve my problem instantly.

Second question, in case answer to first is no:

Is there a way to initialize a new Audio() using as src another Audio that has already downloaded the file?

  • 1
    What about just using the web audio API? https://stackoverflow.com/questions/46926033/create-seamless-loop-of-audio-web – Terry Jan 06 '22 at 00:12

1 Answers1

0

as suggested by @Terry,

I don't think there was a way to do that as i suggested.

I however looked into the web audio API and that worked wonders (including an out-of-the-box seamless loop)