Tob*_*rth 5 html authentication audio
假设我们在这里有一个内容提供者端点,myuri.org/api/auth/sources/{id}
它返回由 id 标识的音乐文件。
路由/api/auth/需要身份验证。在这种情况下,这是通过像这样在请求标头中传递的 JWT 来完成的Authentication: Bearer <token>。
如果身份验证不存在,我可以只加载一个 html5 音频组件,其中包含一个虚构的音乐文件的来源,其 id37像这样
<audio controls>
<source src="myuri.org/api/sources/37" type="audio/mp3">
</audio>
Run Code Online (Sandbox Code Playgroud)
但由于我需要身份验证;这将如何工作?并提供任何可能的解决方案;寻找/跳过仍然有效吗?
..我花了更多时间寻找其他答案并找到了这篇文章。我想这是不可能的。
以下代码是遵循所描述逻辑的概念证明。但它没有使用 html5 音频组件,而是使用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();
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助别人。