假设我们这里有一个内容提供者端点myuri.org/api/auth/sources/{id}
它返回由 id 标识的音乐文件。
路线/api/auth/
需要身份验证。在本例中,这是通过在请求标头中传递 JWT 来完成的,如下所示Authentication: Bearer <token>
.
如果没有身份验证,我可以加载一个 html5 音频组件,其中包含带有 id 的虚构音乐文件的源37
like so
<audio controls>
<source src="myuri.org/api/sources/37" type="audio/mp3">
</audio>
但由于我需要身份验证;这会如何运作?以及提供的任何可能的解决方案;寻找/跳过仍然有效吗?
..我花了更多时间寻找其他答案并发现这个帖子 https://stackoverflow.com/questions/9299189/send-custom-http-request-header-with-html5-audio-tag/9992962#9992962。我想这是不可能的。
替代解决方案
以下代码是遵循所描述逻辑的概念证明。但它没有使用 html5 音频组件,而是使用网络音频 API https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Using_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();
我希望这可以帮助别人。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)