1

In our app we have the following HTML code

<audio controls="controls" src="http://user:password@server:port/searchapi?command=replay&amp;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:

  1. Instead of that authorization execute JS code which sends a GET request
  2. In a src attribute put the file itself.

The code looks like this:

var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'server:port/searchapi?command=replay&amp;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.

Joe D
  • 13
  • 3

1 Answers1

1

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...

Joe D
  • 44
  • 1
  • 10