簡體   English   中英

如何獲取 JavaScript 中創建的音頻元素的文件大小?

[英]How can I get the file size of a created audio element in JavaScript?

如何獲取非 DOM 創建的音頻元素的文件大小?

我想我可以使用 HTML5 文件 API – 根據客戶使用 HTML5 檢查文件大小? – 但它似乎不適用於不在 DOM 中的元素。

我在下面創建了一個示例——請參見console.log(audio_file.files[0].size); ,這給出了一個錯誤:

類型錯誤:audio_file.files 未定義

 // 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);

我嘗試通過進行fetch調用並從 blob 計算文件的大小。

但缺點是,在文件完全加載為給定 mp3 url 的響應頭之前,我們無法知道文件的大小,沒有任何與大小相關的信息。

在這里,我已經將音頻數據提取到音頻元素后進行了設置,但這不是必需的。 我只是添加它來播放音頻文件。

(您必須等到文件加載后才能看到運行代碼片段的結果。)

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM