获取音频src url状态JS

时间:2019-02-01 10:30:41

标签: javascript jquery html5-audio soundcloud

我正在从Soundcloud API将音频流传输到播放器。

GL_GREATER

我有<audio></aidio> <source src="soundcloud-track-url"></source> <audio>标签的onerror eventListener。

如果未从源代码加载流,则会触发<source>,但是我不知道如何验证这是因为per day limit已经到达。

所以我的逻辑是:onerror我想进一步拆分src负载时出现错误,if这是因为“限制”-这样做,if不是因为的“限制”-做到这一点。

如果每天均达到限制,Soundcloud API将返回HTTP 429响应代码“请求太多”。

如何利用“ HTTP 429”信息获得预期结果?

2 个答案:

答案 0 :(得分:0)

由于您在问题中没有提供任何线索,我猜您正在使用AJAX与SoundCloud进行通信。

鉴于此,您需要检查status(XMLHttpRequest)对象上的xhr属性。

xhr.onreadystatechange = function( e ) {

    // `xhr.status` is what you're looking for.
    // you can check if it matches your expected 429 or not 
    if ( xhr.status == 429 && xhr.readyState == 4 ) {

        // do whatever you want

    }

}

更新:由于一开始使用的方法错误,我建议您阅读this same problem个人所拥有的内容,并看看他们是如何解决的。

答案 1 :(得分:0)

您需要将类似event的属性传递给错误处理程序,然后获取其target属性,该属性指向引发错误的HTML元素。

一旦有了元素本身,就很容易使用.getAttribute('src')来获取其src属性。

一旦有了src属性,就可以fetch对其进行检查,并检查该请求的错误状态。

document.getElementById("mySource").onerror = event => {
    var sourceElement = event.target;
    var audioURL = sourceElement.getAttribute("src");

    fetch(audioURL).then(function(response) {
        alert(response.status);
    });
};

这是如何工作的沙盒:

https://codepen.io/pghiran/pen/GzWdmg?editors=1010