How to force the browser to download only part of a file in an audio element?

I have an audio element that I control through JavaScript:

<audio preload="metadata" src="myfile.mp3" />

<button type="button">Play/Pause</button>

// JS logic not relevant to the question

Let’s say myfile.mp3 is a 5-minute audio and after I play the first 10 seconds of it, I call pause() to prevent the rest of it from being played. It seems like the browser continues downloading the rest of the file. How can I prevent this from happening and download only a specific chunk of the file?

>Solution :

Try this:

const mediaElement = document.querySelector("#myMediaElementID");

By removing the media element’s src attribute and invoking the load() method, you release the resources associated with the audio/video, which stops the network download. You must call load() after removing the attribute, because just removing the src attribute does not invoke the load algorithm.

Leave a Reply