5 javascript akamai html5-video html5-audio
我正在尝试使用 html5 音频标签播放音频文件。
玩的不错...
但是出于某种原因,要求浏览器为源发出请求,必须包含浏览器(在我的情况下为 safari)未添加的特定标头。(正如我看到的 chrome 添加的那样)
标题是: Accept-encoding: gzip
我怎样才能做到这一点?
我不想事先下载整个文件......我想要音频标签来处理它,并带有一个新的标题。
document.getElementById("audio").load();
document.getElementById("audio").play();Run Code Online (Sandbox Code Playgroud)
<audio id="audio" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/7/7b/FurElise.ogg/FurElise.ogg.mp3"> <audio>
Run Code Online (Sandbox Code Playgroud)
再一次,当此代码运行时,我只想修改为此发出的每个请求的标头...
注意:
当您添加源并加载 chrome 时,浏览器会发出“范围请求”请求媒体文件的后续部分,以便在某些数据可用时立即开始播放,但是,我使用的 CDN 需要这些请求具有此特定标头,问题是在 chrome 中,此标头是由 chrome 本身添加的,而在 safari 中则不然,因此我想拦截浏览器在调用load()媒体元素并添加标头时发出的这些请求。我不想在付款之前下载整个文件,我知道这可行,但这违背了目的。
由于您想要做的是加载然后播放,那么如何将您的请求与XMLHttpRequest样式模式结合起来,使用类似的东西fetch?
喜欢:
超文本标记语言
<!-- just an indicator, in case the file is large -->
<div id="loading"><em>File is loading. Please wait...</em></div>
<!-- initially hide the audio tag. Also, change the 'src' to 'data-src' so it doesn't automatically load -->
<audio id="audio" style="display: none;" data-src="https://upload.wikimedia.org/wikipedia/commons/transcoded/7/7b/FurElise.ogg/FurElise.ogg.mp3" controls></audio>
Run Code Online (Sandbox Code Playgroud)
JavaScript
// define variables
var audioEl = document.getElementById("audio");
function fetchAudioFile() {
// go get the file
var requestObj = new Request(audioEl.dataset.src, {
method: 'GET',
headers: {
'Accept-encoding': 'gzip' // add your header(s)
},
referrerPolicy: 'no-referrer'
});
fetch(requestObj).then(function(response) {
return response;
}).then(async function(outcome) {
const blob = await outcome.blob();
// convert our blob to a url that can be used by the audio tag
const url = window.URL.createObjectURL(blob);
// replace the source
audioEl.src = url;
// hide the helpful text
document.getElementById("loading").style["display"] = "none";
// show the audio tag
audioEl.style["display"] = "block";
// play it immediately
audioEl.play();
});
};
// get the file
fetchAudioFile();
Run Code Online (Sandbox Code Playgroud)
希望这有帮助。请注意,根据浏览器的不同,有时音频可能不会自动播放,除非用户首先与页面交互或明确授予许可。
| 归档时间: |
|
| 查看次数: |
694 次 |
| 最近记录: |