点播播放示例(MP4)
这是最常见的“给一个 MP4 地址 → 播放、暂停、拖动进度”的例子。它使用原有自动选核,不需要先决定 MSE、WebCodec 或 WASM。先用一个已知能正常播放的 MP4 跑通,再替换成你的文件。
1. 放好文件
把文件放成下面的结构,并通过 HTTP 服务访问。可从 GitHub CDN 下载自生成的普通 H.264 + AAC 测试视频并保存为 media/video.mp4,也可换成自己的文件;代码里的 URL 必须与真实路径一致。VR360 和 HEVC 样本见测试素材与 FFmpeg 推流。
text
demo/
├── index.html
├── media/video.mp4 ← 换成你的 MP4
└── output/
├── h265web.js
├── h265web_wasm.js
└── h265web_wasm.wasm如果 MP4 开始加载很慢,可以先检查 moov 和服务器 Range。只调整 MP4 索引位置、不重新编码的命令如下;输出到新文件,不要覆盖原文件:
bash
ffmpeg -i ./media/video.mp4 -map 0 -c copy -movflags +faststart ./media/video-faststart.mp4moov 在文件尾并非必然不能播放;完整排查见 QA WIKI。
2. 复制 index.html
html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>MP4 点播示例</title>
<script src="./output/h265web.js"></script>
</head>
<body>
<div id="player"></div>
<button id="play" disabled>播放</button>
<button id="pause">暂停</button>
<button id="seek" disabled>跳到第 10 秒</button>
<button id="sound">打开声音</button>
<p id="status">正在加载 MP4…</p>
<script>
const mediaUrl = './media/video.mp4'; // 也可以换成有权限访问的完整 HTTP(S) URL。
const status = document.getElementById('status');
const playButton = document.getElementById('play');
const seekButton = document.getElementById('seek');
const player = H265webjsPlayer();
// 先绑定回调,再 build()、load_media();ready 不会自动开始播放。
player.on_ready_show_done_callback = () => {
playButton.disabled = false;
seekButton.disabled = false;
status.textContent = '首帧就绪,请点击播放。';
};
player.video_probe_callback = (info) => console.log('编码/时长等信息', info);
player.on_seek_done_callback = (seconds) => {
status.textContent = `已跳到 ${seconds.toFixed(1)} 秒`;
};
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,
// 不指定 core,让 SDK 根据片源和浏览器能力自动选核。
});
if (ok) {
player.set_voice(0); // 初始静音;想听声音时让用户点击按钮。
player.load_media(mediaUrl);
} else {
status.textContent = '播放器创建失败:检查 SDK 文件路径。';
}
playButton.onclick = () => player.play();
document.getElementById('pause').onclick = () => player.pause();
seekButton.onclick = () => player.seek(10); // 秒;太短的视频请改为更小的值。
document.getElementById('sound').onclick = () => player.set_voice(1);
window.addEventListener('beforeunload', () => player.release());
</script>
</body>
</html>3. 打开与排查
在 demo/ 目录运行 python3 -m http.server 8080,访问 http://localhost:8080/。auto_play: false 时必须点“播放”。如果首帧已就绪但画面黑,先看文件第 0 帧是否本来就是黑色;如果始终不 ready,检查 Network 中 MP4 请求的状态、类型、Range 和 QA WIKI。