WebRTC 播放示例
这里演示 WebRTC 拉流播放,不是推流。最推荐传入 WHEP 播放地址;WHIP 是推流地址,不能当播放地址使用。播放器仍是同一个 H265webjsPlayer(),无需第二套公开 API。
1. 先准备一条真实的流
先运行 ZLMediaKit,再把测试文件推到 live/test。下面的命令需要本机安装 FFmpeg,并把 ./media/live.mp4 换成真实文件。可以从 GitHub CDN 下载自生成的普通 H.264 + AAC 测试视频并保存为 ./media/live.mp4;测试素材与 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确认 ZLMediaKit 的 WHEP 地址可访问;如果媒体服务器在另一台机器,下面代码里的 127.0.0.1 必须改成那台机器的地址。ZLMediaKit 从 RTMP 转 WebRTC 时建议按入门文档设置 modify_stamp=1;浏览器只能播放它成功协商的编码。
2. 复制 index.html
目录里还需要同一次构建生成的 output/h265web.js、h265web_wasm.js、h265web_wasm.wasm。用 HTTP 服务打开此页面,不要用 file://。
html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>WebRTC 播放示例</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">等待 WebRTC 画面…</p>
<script>
// WHEP 是拉流入口;先确保 ZLMediaKit 上真的存在 live/test。
const whepUrl = 'http://127.0.0.1/index/api/whep?app=live&stream=test';
const status = document.getElementById('status');
const playButton = document.getElementById('play');
const player = H265webjsPlayer();
// 回调要在 build() 之前绑定,方便看到首帧和错误。
player.on_ready_show_done_callback = () => {
playButton.disabled = false;
status.textContent = 'WebRTC 首帧已就绪,点击播放。';
};
player.video_probe_callback = (info) => console.log('媒体信息', info);
player.on_error_callback = (error) => {
status.textContent = `WebRTC 错误:${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,
// 不写 core:SDK 会根据 WHEP URL 自动选 WebRTC。
// 只想强制 WebRTC 时,可在这里增加 core: 'webrtc'。
});
if (ok) {
player.set_voice(0); // 演示初始静音;点击“打开声音”恢复。
player.load_media(whepUrl);
} 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. 常见误区
- 播放用 WHEP,推流用 WHIP;
webrtc://是 SDK 兼容写法,最先测试 WHEP。 - WebRTC 直播通常固定 1 倍速,不支持普通点播式 Seek。
127.0.0.1指打开网页的那台机器;远程浏览器访问你的服务器时必须换地址,并检查信令 CORS/HTTPS/ICE。- 画面跳动先确认 ZLMediaKit 时间戳设置和源流,再看 QA WIKI。