【问题标题】:How can I detect the URL is mp4 or m3u8 and play it on browser?如何检测 URL 是 mp4 还是 m3u8 并在浏览器上播放?
【发布时间】:2022-01-24 20:13:47
【问题描述】:

我正在使用 React,我有 2 种类型的视频要播放,1 种是 m3u8,1 种是 mp4。

我有一组电影系列剧集,但它与 m3u8 和 mp4 混合在一起。

那么我怎样才能检测到它是什么,以便它可以在浏览器上显示它。

我正在使用可以轻松播放 m3u8 的 ReactHlsPlayer,但问题是如果它是包含 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 并使用合适的解决方案播放它?谢谢。

【问题讨论】:

  • 我建议你试试看能不能从url获取MIME类型
  • 您是指 MIME 类型 -(IANA 媒体类型)吗?
  • 是的,我就是这么说的;)
  • 谢谢,我马上去看看。
  • @Bunny 你发现了什么?你能根据 URL 字符串区分类型吗?

标签: javascript html reactjs


【解决方案1】:

根据我的情况,我只需要识别/区分我得到的 URL 是否是 video/mp4 类型(然后是 m3u8),如果你的情况相似或有更多类型需要识别/区分,我认为它会以同样的方式工作。

首先我快速浏览一下@ControlAltDel 提供的MIME Types,然后我对如何获取URL 请求进行了更多研究,这导致了XMLHttpRequest,因为我使用POSTMAN 解决问题以查看我得到的 URL 请求的标头,事情变得更清楚了,我需要进入 HEADER 并从中获取 Content-Type。

所以这里有一个快速代码,我可以用它来获得我想要的东西。

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();

【讨论】:

    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 2023-03-28
    • 2015-06-20
    • 2011-04-04
    • 2013-08-20
    相关资源
    最近更新 更多