How to get Blob data from an existing audio element with Javascript

故事扮演 提交于 2020-01-24 09:12:40

问题


I have a mp3 file for play it in my View. I already know location of that mp3 files in my server , audio element is working good , I can play this mp3. but I need to get blob data from this audio element. I found so many example on web, but everyone teach only when we upload a file from <input> element.

I just need to learn how to get binary data from an existing audio element like this :

<audio id="myAudio" src="/Media/UserData/mp3DataFolder/5f67889a-0860-4a33-b91b-9448b614298d.mp3"></audio>

Thanks from now.


回答1:


You can simply fetch this url and set the responseType of your request to "blob".

var aud = document.getElementById('aud');
var xhr = new XMLHttpRequest();
xhr.open('GET', aud.src);
xhr.responseType = 'blob';
xhr.onload = e => console.log(xhr.response);
xhr.send();
<audio src="https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3" id="aud" controls>

Or using the fetch API:

var aud = document.getElementById('aud');
fetch(aud.src)
  .then(response => response.blob())
  .then(console.log);
<audio src="https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3" id="aud" controls>

Of course this assumes that the server holding your audio file allows you to fetch it from client (which it should in your case since you shown relative urls).




回答2:


Hi you could first convert it to base 64 then blob:

key method:

var bufferToBase64 = function (buffer) {
    var bytes = new Uint8Array(buffer);
    var len = buffer.byteLength;
    var binary = "";
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
};

[ https://codepen.io/xewl/pen/NjyRJx ]

Then follow this answer to create the blob.

Javascript make audio blob

demo: https://jsfiddle.net/sanddune/uubnnr0w/



来源:https://stackoverflow.com/questions/52925966/how-to-get-blob-data-from-an-existing-audio-element-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!