I'm trying to make a function that checks a resource that the user provides, to see if it is a valid audio file.
Everything I've found on here, is related to checking a files MIME type after uploading a file. That is not my goal here.
//insert MIME type checking function here
const urlParams = new URLSearchParams(window.location.search);
const audioURL = urlParams('audiourl') // get audiourl from query (example.com/?audiourl=https://example.com/audio.wav)
if (mimetypecheck()) { // function to check mime type here
var audio = new Audio(audioURL);
audio.play();
} else {
//tell user invalid audio url, or unsupported audio type
}
As it has been said in comments, the only way to check that a resource points to some playable media, is to actually try to play it.
A MIME type won't tell you much, moreover for audio/video media:
you can't be 100% sure that what the container (which is declared by the MIME type) really contains, it could very well be encoded in a codec that the browser can't decode, even if it wrapped in a container the browser should know.
This means that even though a simple HEAD request could tell you for some URLs what the server would send in the Content-Type headers, that wouldn't tell you exactly if the browser would be able to play it. And given most server won't let you read these headers anyway, that doesn't worth the cost of trying to implement this.
For your case the best is thus to try to play it.
So you can rewrite your code to
const urlParams = new URLSearchParams(window.location.search);
const audioURL = urlParams('audiourl') // get audiourl from query (example.com/?audiourl=https://example.com/audio.wav)
const audio = new Audio(audioURL);
audio.onerror = (evt) => {
//tell user invalid audio url, or unsupported audio type
};
audio.play();
Note that we could also have bound to the catch()
method of the Promise returned by the HTMLMediaElement.play()
method, but it could actually fire for an other reason (e.g if the user never did interact with the page before in Chrome, or if this code is not in direct response to an user-gesture in Safari). If you are sure only invalid URLs could be the reason for a failure to play, then you could do
const audio = new Audio(audioURL);
audio.play().catch( () => {
//tell user invalid audio url, or unsupported audio type
});