我用的是React,我想播放两种类型的视频,一种是m3u8,一种是mp4。
我有一套系列电影,但它与m3u8和mp4混为一谈。
所以我怎样才能发现它是什么,这样它就可以在浏览器上显示它。
我使用的ReactHlsPlayer可以轻松地播放m3u8,但问题是如果是包含mp4文件的URL,它拒绝在浏览器上读取和显示。
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')
);如果我用
<source src="url-that-contain-mp4" type="video/mp4">它将完美地读取mp4 URL,但是它只会读取mp4,并拒绝m3u8
那么,我是否可以创建一个函数或组件来检测我的URL是m3u8还是mp4,并使用合适的解决方案来播放它呢?谢谢。
发布于 2021-12-25 02:33:20
根据我的情况,我只需要识别/鉴别我得到的URL是否为m3u8 /MP4(然后是m3u8),如果您的情况类似或有更多类型需要识别/歧视,我认为它的工作方式是相同的。
首先,我快速查看@ControlAltDel提供的MIME类型,然后对如何接受XMLHttpRequest请求做了更多的研究,这导致了XMLHttpRequest,因为我与邮递员一起看到我得到的URL请求的标题,事情变得更清楚了,我需要进入标题并从其中获取内容类型。

所以,这里有一个快速的代码,我做的事情,我想要的。
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();https://stackoverflow.com/questions/70468788
复制相似问题