Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load html5 audio from dynamic content provider with authentication

Let's assume we have a content provider endpoint here myuri.org/api/auth/sources/{id} which returns music files identified by id.

The route /api/auth/ requires authentication. In this case this is done with a JWT passed in the request header like so Authentication: Bearer <token>.

If the authentication wouldn't be there, I could just load a html5 audio component with the source for a fictional music file with id 37 like so

<audio controls>
  <source src="myuri.org/api/sources/37" type="audio/mp3">
</audio>

But since I need authentication; how would this work? And for any possible solution provided; does seeking/skipping still work?

like image 718
Tobias Würth Avatar asked Jan 16 '18 09:01

Tobias Würth


1 Answers

.. I spent some more time searching for other answers and found this post. I guess this is not possible this way.

Alternative Solution

The following code is a proof of concept following the described logic. But instead of using the html5 audio component, it uses the Web Audio Api.

let url = "myuri.org/auth/sources/37";

// create context
let audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// create source
let source = audioCtx.createBufferSource();

// route source
source.connect(audioCtx.destination);

// prepare request
let request = new XMLHttpRequest();
request.open('GET', url, true /* async */ );
request.responseType = 'arraybuffer';

request.onload = function () {
    // on load callback

    // get audio data
    let audioData = request.response;

    // try to decode audio data
    audioCtx.decodeAudioData(audioData,
        function (buffer) {
            // on success callback
            console.log("Successfully decoded");

            // set source
            source.buffer = buffer;

            // .. do whatever you want with the source
            // e.g. play it
            source.start(0);
            // or stop
            source.stop();
        },
        function (e) {
            // on error callback
            console.log("An error occurred");
            console.log(e);
        });
};

request.setRequestHeader("Authorization", `Bearer ${authenticationToken}`);
request.send();

I hope this helps someone.

like image 59
Tobias Würth Avatar answered Nov 15 '22 05:11

Tobias Würth