在我们的应用中,我们具有以下HTML代码
<audio controls="controls" src="http://user:password@server:port/searchapi?command=replay&id=9203732824369002191_2"> Your browser does not support the HTML5 Audio element. </audio>
它转到上面的URL,并应该获得音频文件。
但是,并非所有浏览器都支持它,因此我们决定执行以下操作:
代码如下:
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'server:port/searchapi?command=replay&id=9203732824369002191_2', false);
myRequest.setRequestHeader('Authorization', 'Basic ' + btoa('user:password'));
myRequest.send();
问题是,如何在呈现页面时在页面上执行它?我的意思是将代码直接放在src
标签名称中?
还有,有什么方法可以动态确定mime类型? In the answer是经过硬编码的,并且它们处理图像而不是音频。有区别吗?
我写了以下内容(没有身份验证):
<audio id= "audioElement" controls="controls" [src]="getAudio()"> Your browser does not support the HTML5 Audio element. </audio>
<script>
function getAudio()
{
var oReq = new XMLHttpRequest();
oReq.open('GET', 'https://upload.wikimedia.org/wikipedia/ru/6/62/Meow.ogg', true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent)
{
var arrayBuffer = oReq.response;
if (arrayBuffer) {
var u8 = new Uint8Array(arrayBuffer);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
var mimetype="audio/ogg";
document.getElementById("audioElement").src="data:"+mimetype+";base64,"+b64encoded;
oReq.send(null);
}
}
</script>
但这不起作用。
出什么问题了?
谢谢。
答案 0 :(得分:0)
好吧,看来实现这种行为的正确方法如下:
<audio id= "audioElement" controls="controls"> Your browser does not support the HTML5 Audio element. </audio>
<script>
window.onload = function()
{
var oReq = new XMLHttpRequest();
oReq.open('GET', 'https://upload.wikimedia.org/wikipedia/ru/6/62/Meow.ogg', true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent)
{
var arrayBuffer = oReq.response;
if (arrayBuffer)
{
var u8 = new Uint8Array(arrayBuffer);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
var mimetype="audio/ogg"; // or whatever mime type is
document.getElementById("audioElement").src="data:"+mimetype+";base64,"+b64encoded;
}
}
oReq.send(null);
}
</script>
希望它也可以使用基本身份验证...