gpt4 book ai didi

javascript - 如何在设置音频 src 时发送 header ?

转载 作者:行者123 更新时间:2023-12-03 09:38:18 28 4
gpt4 key购买 nike

我正在尝试使用 html5 音频标签播放音频文件。
玩的不错...
但由于某种原因,要求浏览器为源发出请求,必须包含浏览器(在我的情况下为 safari)未添加的特定 header 。 (我看到 chrome 添加的地方)
标题是:Accept-encoding: gzip我怎样才能做到这一点?
我不想事先下载整个文件...我想要音频标签来处理它,并带有一个新的标题。

document.getElementById("audio").load();
document.getElementById("audio").play();
<audio id="audio" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/7/7b/FurElise.ogg/FurElise.ogg.mp3"> <audio>

再一次,当这段代码运行时,我只想修改为此发出的每个请求的 header ......
备注 :
当您添加源并加载到 chrome 中时,浏览器会发出“范围请求”,要求媒体文件的后续部分,以便它可以在一些数据可用时立即开始播放,但是,我使用的 CDN 需要那些请求拥有这个特定的 header ,问题是在 chrome 中这个 header 是由 chrome 本身添加的,而在 safari 中不是,因此我想拦截浏览器在调用 load() 时发出的这些请求在媒体元素上并添加标题。
我不想在付款之前下载整个文件,我知道这行得通,但这违背了目的。

最佳答案

既然您要做的是加载然后播放,那么将您的请求与 XMLHttpRequest 结合起来怎么样?样式模式,使用类似 fetch ?
喜欢:
HTML

<!-- 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>
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();
希望这会有所帮助。请注意,根据浏览器的不同,有时音频可能会 不是 自动播放,除非用户首先与页面交互或明确授予权限。

关于javascript - 如何在设置音频 src 时发送 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65250822/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com