如何使用Javascript从现有音频元素中获取Blob数据 [英] How to get Blob data from an existing audio element with Javascript
问题描述
我有一个mp3
文件,可以在我的视图中播放它.我已经知道服务器中mp3
文件的位置,音频元素运行良好,我可以播放此mp3
.但我需要从该音频元素中获取Blob数据.我在网络上发现了很多示例,但是每个人都只有在我们从<input>
元素上载文件时才能教书.
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.
我只需要学习如何从这样的现有audio
元素中获取二进制数据:
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>
从现在开始.
推荐答案
您可以简单地获取此URL并将请求的responseType设置为"blob"
.
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>
或使用获取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>
当然,这是假定保存音频文件的服务器允许您从客户端获取它(由于您显示了相对URL,因此在您的情况下应该如此).
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).
这篇关于如何使用Javascript从现有音频元素中获取Blob数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!