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?
.. I spent some more time searching for other answers and found this post. I guess this is not possible this way.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With