In our app we have the following HTML code
<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>
It goes to the URL above and supposed to get an audio file.
However, it's not supported in every browser, so we decided to do the following:
The code looks like this:
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();
The question is how do we execute it on a page while it's rendering? I mean put that code directly in src
tag name?
Also, is there any way to determine mime-type dynamically? In the answer it's hardcoded and they process an image, not audio. Is there a difference?
I wrote the following (without auth):
<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>
But it doesn't work.
What's the problem?
Thanks in advance.
Well , it seems the the proper way to implement such behaviour is the following:
<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>
Hopefully, it will work with basic auth too...