I'm using React, I have 2 types of video that I want to play, 1 is m3u8 and 1 is mp4.
I have a set of episodes of film series, but it mixed with m3u8 and mp4 together.
So how can I detect whatever it is so it can display it on Browser.
I'm using ReactHlsPlayer that can easily play the m3u8, but the problem is if it's the URL that contains an mp4 file, it refuses to read and display it on my browser.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ReactHlsPlayer from 'react-hls-player';
ReactDOM.render(
<React.StrictMode>
<App />
<ReactHlsPlayer
src = "url-that-contain-m3u8"
autoPlay = {false}
controls = {true}
width = "100%"
height = "auto"
/>
</React.StrictMode>,
document.getElementById('root')
);
If I use
<source src="url-that-contain-mp4" type="video/mp4">
It'll read the mp4 URL perfectly, but then, it'll only read the mp4, and refuse the m3u8
So is there a way I can create a function or a component that can detect if my URL is m3u8 or mp4 and play it with a suitable solution? Thanks.
Based on my condition, I just need to recognize/discriminate if the URL that I get is type video/mp4 or not (it'll be the m3u8 then), if your case is similar or has more types that need to recognize/discriminate, I think it'll work the same way.
First I take a quick look at MIME Types that @ControlAltDel provide, and then I do a little bit more research on how to take the URL request, which leads to XMLHttpRequest due to I workaround with POSTMAN to see the Header of the URL Request that I get, things become clearer, that I need to get into the HEADER and get the Content-Type from it.
So here's a quick code that I do to get things that I want.
let URL = the-url-that-contain-mp4-or-m3u8
// Make a function or variable to get the URL you want, in my case it's the episode URL.
let xhr = new XMLHttpRequest();
// Requests the headers that would be returned if the HEAD request's URL was instead requested with the HTTP GET method
xhr.open('HEAD', url, true);
xhr.onload = function() {
// In here I get the Content Type from the HEAD of the response
let contentType = xhr.getResponseHeader('Content-Type');
if (contentType == 'video/mp4'){
console.log(contentType);
console.log("This is mp4 video")
//Function to play mp4 file
}
else {
console.log("This is m3u8 then")
// Function to play HLS m3u8 file
}
};
xhr.send();