Reputation: 14153
How can I get the file size of a non-DOM created audio element?
I thought I could use the HTML5 File API – as per Client Checking file size using HTML5? – but it doesn't seem to be working for elements not in the DOM.
I've created an example below – see the line console.log(audio_file.files[0].size);
, which gives an error of:
TypeError: audio_file.files is undefined
// Create a non-dom allocated Audio element
var audio_file = document.createElement('audio');
// Define the URL of the MP3 audio file
audio_file.src = "https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3";
// Once the metadata has been loaded, display the duration in the console
audio_file.addEventListener('loadedmetadata', function(){
// Obtain the duration in seconds of the audio file
var duration = audio_file.duration;
const duration_hhmmss = new Date(duration * 1000).toISOString().substr(11, 8);
console.log("The duration of the song is of: " + duration_hhmmss);
console.log(audio_file.files[0].size);
},false);
Upvotes: 1
Views: 1222
Reputation: 967
I tried by making a fetch
call and calculated the size of the file from blob.
But downside is, we cant know the size of the file until its completely loaded as the response headers of the given mp3 url didnt have any info related to size.
Here I have set the audio data after its fetched to the audio element, but this is not necessary. I just added it to play the audio file.
(You will have to wait till the file has loaded to see result after pressing Run code snippet.)
const audioEl = document.querySelector('audio');
fetch(
"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3"
)
.then((response) => {
// console.log(response);
return response.body
})
.then((data) => {
var reader = data.getReader();
return new ReadableStream({
start(controller) {
return pump();
function pump() {
return reader.read().then(({ done, value }) => {
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
return;
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
return pump();
});
}
}
});
})
.then((stream) => new Response(stream, {headers: {'Content-Type': 'audio/mpeg'}}))
.then((response) => response.blob())
.then(blob => {
// console.log(blob);
const reader = new FileReader();
reader.addEventListener('loadend', () => {
audioEl.src = reader.result; // output of reader.readAsDataURL
});
reader.readAsDataURL(blob);
const sizeInByte = blob.size;
const sizeInMB = sizeInByte / 1024 / 1024;
document.querySelector('#size').innerText = `Size of the loaded audio is ${sizeInMB.toFixed(2)}MB`;
});
<audio controls></audio>
<div id="size"></div>
Upvotes: 1