检查URL是否存在并链接到音频文件



我写了一个测试来验证音频(MP3、WAV(的URL格式是否正确。

现在我想检查两件事:

  1. URL存在
  2. 发出head请求以确保URL链接到音频文件

我该怎么做?我还没有找到任何关于生成head请求的好的JavaScript示例。

// The test being performed    
if (result.onClose === true) {
if(UtilService.isValidUrl(result.url) && UtilService.isValidAudioUrl(result.url)) {
console.log('url is valid')
}
}
// In UtilService
static isValidUrl(urlToCheck: string) {
let url;
try {
url = new URL(urlToCheck);
} catch (_) {
return false;
}
return url.protocol === 'http:' || url.protocol === 'https:';
}
// Unsure how to perform the check here
static isValidAudioUrl(urlToCheck: string) {
const xhr = new XMLHttpRequest();
xhr.open("HEAD", urlToCheck);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
// I'd like it to return a boolean value of true or false in isValidAudioUrl if the response header indicates the media type of the URL is audio and exists
return false;
}

我认为您的音频URL验证功能可能是这样的。其思想是检查Content-type响应标头。对于音频文件,它通常以audio(例如audio/mpeg(开头

function isValidAudioUrl(urlToCheck) {
return fetch(urlToCheck, { method: 'HEAD', mode: 'no-cors' })
.then(res => res.ok && res.headers.get('content-type').startsWith('audio'))
.catch(err => console.log(err.message));
}
// In your code
console.log('validating');
isValidAudioUrl('https://<YOUR_URL>.mp3')
.then(result => console.log(result));

最新更新