Skip to content

直播播放示例(HTTP-FLV / HLS) ​

这是普通直播地址的最小播放页。先有直播流,再打开网页;把地址填进播放器并不会自动创建直播。WebRTC 直播请看单独的 WebRTC 播放示例。

1. 准备直播源和地址 ​

例如运行 ZLMediaKit,并用 FFmpeg 推流到 live/test。把 ./media/live.mp4 换成自己的测试文件,或从 GitHub CDN 将自生成的普通 H.264 + AAC 测试片下载为这个文件名。无需重编码的命令和 VR360 直播地址见测试素材与 FFmpeg 推流:

bash
ffmpeg -stream_loop -1 -re -i ./media/live.mp4 \
  -vf scale=640:360,format=yuv420p \
  -c:v libx264 -preset veryfast -tune zerolatency -bf 0 -g 30 \
  -c:a aac -ar 44100 -ac 2 -f flv \
  rtmp://127.0.0.1/live/test

常见的拉流 URL:

text
HTTP-FLV: http://127.0.0.1/live/test.live.flv
HLS:      http://127.0.0.1/live/test/hls.m3u8

127.0.0.1 是浏览器所在机器。如果浏览器和媒体服务器不在同一台机器,改成媒体服务器实际地址;跨域时服务器要允许 CORS。HLS 有切片延迟,不能仅用它判断低延迟直播效果。

2. 复制 index.html ​

页面旁边放同一次构建的 output/h265web.js、h265web_wasm.js 和 h265web_wasm.wasm,再通过 HTTP 服务访问。

html
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>直播播放示例</title>
  <script src="./output/h265web.js"></script>
</head>
<body>
  <div id="player"></div>
  <button id="play" disabled>播放</button>
  <button id="pause">暂停</button>
  <button id="sound">打开声音</button>
  <p id="status">正在连接直播源…</p>

  <script>
    // 先确认该 URL 能从浏览器所在机器访问,且正在推流。
    const mediaUrl = 'http://127.0.0.1/live/test.live.flv';
    // 要测试 HLS,把上一行改为:
    // const mediaUrl = 'http://127.0.0.1/live/test/hls.m3u8';
    const status = document.getElementById('status');
    const playButton = document.getElementById('play');
    const player = H265webjsPlayer();

    // 回调必须先绑定;缓存中不一定是错误,也可能在等下一段直播数据。
    player.on_ready_show_done_callback = () => {
      playButton.disabled = false;
      status.textContent = '直播首帧就绪,请点击播放。';
    };
    player.on_load_caching_callback = () => { status.textContent = '正在等待直播数据…'; };
    player.on_error_callback = (error) => {
      status.textContent = `直播错误:${error.message || error.code}`;
    };

    const ok = player.build({
      player_id: 'player',
      base_url: './output/',
      wasm_js_uri: 'h265web_wasm.js',
      wasm_wasm_uri: 'h265web_wasm.wasm',
      width: '100%', height: 480,
      auto_play: false, ignore_audio: false,
      hls_strategy: 'auto' // HLS 使用当前主线;不要误选历史 legacy。
    });
    if (ok) {
      player.set_voice(0); // 初始静音,用户点击按钮后再开声音。
      player.load_media(mediaUrl);
    } else {
      status.textContent = '播放器创建失败:检查 SDK 文件路径。';
    }

    playButton.onclick = () => player.play();
    document.getElementById('pause').onclick = () => player.pause();
    document.getElementById('sound').onclick = () => player.set_voice(1);
    window.addEventListener('beforeunload', () => player.release());
  </script>
</body>
</html>

3. 常见误区 ​

  • 直播 URL 没有流时,播放器只能等待或报错;先到媒体服务器确认 live/test 正在推送。
  • auto_play: false 时,首帧就绪后还要点“播放”。
  • 普通直播不保证能 Seek;只有服务器提供可回看范围时才考虑 Seek。
  • HLS 请保持 hls_strategy: 'auto' 或 'mainline';请求失败时先查 Network、CORS 和 QA WIKI。