You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过video标签事件获取并处理.m3u8/.ts文件的字符串内容?

如何在JavaScript中解析并处理M3U8播放列表内容

能不能通过video标签事件获取这些信息?

直接通过video标签的原生事件无法获取M3U8的原始内容或解析后的片段信息。video标签(搭配HLS播放时)仅负责底层加载播放媒体片段,不会向上层JS暴露播放列表的具体解析细节。

可行的实现方法

方法1:手动下载并解析M3U8内容

直接通过fetch请求M3U8文件地址,拿到原始字符串后自行解析为JSON格式:

async function parseM3U8(url) {
  const response = await fetch(url);
  const m3u8Text = await response.text();
  const lines = m3u8Text.split('\n').filter(line => line.trim() !== '');
  
  const playlist = {
    targetDuration: null,
    version: null,
    mediaSequence: null,
    playlistType: null,
    segments: []
  };
  
  let currentSegmentDuration = null;
  
  for (const line of lines) {
    if (line.startsWith('#EXT-X-TARGETDURATION:')) {
      playlist.targetDuration = parseFloat(line.split(':')[1]);
    } else if (line.startsWith('#EXT-X-VERSION:')) {
      playlist.version = parseInt(line.split(':')[1]);
    } else if (line.startsWith('#EXT-X-MEDIA-SEQUENCE:')) {
      playlist.mediaSequence = parseInt(line.split(':')[1]);
    } else if (line.startsWith('#EXT-X-PLAYLIST-TYPE:')) {
      playlist.playlistType = line.split(':')[1];
    } else if (line.startsWith('#EXTINF:')) {
      currentSegmentDuration = parseFloat(line.split(',')[0].split(':')[1]);
    } else if (!line.startsWith('#')) {
      playlist.segments.push({
        url: line.trim(),
        duration: currentSegmentDuration
      });
      currentSegmentDuration = null;
    }
  }
  
  return playlist;
}

// 使用示例
parseM3U8('你的M3U8文件地址.m3u8').then(playlist => {
  console.log('解析后的播放列表:', playlist);
  // 此处可处理解析后的JSON数据
});

方法2:借助HLS库解析

如果项目已使用HLS.js这类HLS播放库,可以利用其API直接获取解析后的播放列表信息:

const video = document.getElementById('你的video元素ID');
const hls = new Hls();

hls.loadSource('你的M3U8文件地址.m3u8');
hls.attachMedia(video);

hls.on(Hls.Events.MANIFEST_PARSED, () => {
  // 解析完成后读取播放列表数据
  const manifest = hls.manifest;
  const playlistInfo = {
    targetDuration: manifest.targetDuration,
    version: manifest.version,
    mediaSequence: manifest.mediaSequence,
    playlistType: manifest.playlistType,
    segments: manifest.urls.map((url, index) => ({
      url: url,
      duration: manifest.segments[index].duration
    }))
  };
  
  console.log('HLS.js解析后的播放列表:', playlistInfo);
});

注意事项

  • 跨域问题:若M3U8文件与页面不在同一域名下,需确保服务器配置了CORS规则允许当前域名访问。
  • 动态播放列表:如果是直播类M3U8(非VOD),播放列表会动态更新,需要监听对应事件或定时重新解析。

内容的提问来源于stack exchange,提问作者Younghun Jung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:41:41