user10294268
user10294268

Reputation:

How to check using javascript if URL contains video (but not audio) or audio (but not video) on browser (client side)?

I'm trying using these 2 simple functions to check if URL contains audio or video:

        //For video
        var video = document.createElement("video");
        video.setAttribute("src", url);
        video.addEventListener("canplay", function() {
            console.log("video true");
        });
        video.addEventListener("error", function() {
            console.log("video false");
        });

        //For audio
        var audio = new Audio();
        audio.setAttribute("src", url);
        audio.addEventListener("canplay", function() {
            console.log("audio true");
        });
        audio.addEventListener("error", function() {
            console.log("audio false");
        });

The problem is both of them returns true for both valid audio and video URLs, What's the solution?

Upvotes: 2

Views: 3670

Answers (1)

user10294268
user10294268

Reputation:

So after a deep research, I found that (in HTML) audio is actually a video with no dimensions, so simply you can use this:

var video = document.createElement("video");
video.setAttribute("src", url);
video.addEventListener("canplay", function() {
    console.log("video true");
    console.log(video.videoHeight);
});
video.addEventListener("error", function() {
    console.log("video false");
});
//audio => video true
//         0
//video => video true
//         1080

Upvotes: 5

Related Questions