跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

在浏览器中完成首次 WebRTC 广播

使用浏览器原生 WebRTC,无需第三方库,通过 WHIP 将网络摄像头广播到 Cloudflare Stream,并通过 WHEP 回放。

最后更新 查看 MarkdownAgent 设置

本教程介绍如何使用 WHIP ↗ 从浏览器向 Cloudflare Stream 广播超低延迟直播视频,并使用 WHEP ↗ 在浏览器中回放。广播端和播放端都使用浏览器内置的 WebRTC API——无需安装库,也无需外部应用。

完成后,您将得到一个基本的 HTML 页面:它会捕获摄像头和麦克风,推流到直播输入,并以亚秒级延迟回放同一路流。完成本演练应不超过 15 分钟。

WHIP 和 WHEP 是面向 WebRTC 的简单基于 HTTP 的信令协议。在这两种情况下,此代码都会创建 RTCPeerConnection ↗,生成本地会话描述(SDP offer),通过一次 HTTP POST 将该 offer 发送到 Cloudflare URL,并应用 Cloudflare 返回的 SDP answer。整个交换只有一次请求和一次响应,因此您不需要自己的信令服务器。

开始之前

要完成本教程,您需要:

  • 具备以下任一条件,以便创建直播输入:
    • 付费 Stream 订阅。
    • Pro 或 Business zone 套餐——这些套餐包含 100 分钟视频存储和 10,000 分钟视频交付。
    • 已启用 Stream 的企业合同。
  • 带摄像头和麦克风的现代浏览器。
  • 通过 https 或从 localhost 提供页面。

1. 创建直播输入

每次广播都针对一个直播输入。可通过以下任一方式创建:

响应包含本教程将使用的两个 URL:

向 /live_inputs 发送 POST 请求的 API 响应json
{
  "uid": "1a553f11a88915d093d45eda660d2f8c",
  ...
  "webRTC": {
    "url": "https://customer-<CODE>.cloudflarestream.com/<SECRET>/webRTC/publish"
  },
  "webRTCPlayback": {
    "url": "https://customer-<CODE>.cloudflarestream.com/<INPUT_UID>/webRTC/play"
  },
  ...
}
  • webRTC.url 是您广播到的 WHIP 端点。广播密钥是此 URL 的一部分, 因此请将其视作 stream key,仅分享给正在广播的人。
  • webRTCPlayback.url 是观众播放所用的 WHEP 端点,除非您已在该输入上启用 signed URLs(本文不涵盖)。

复制这两个 URL。您将把它们粘贴到下方代码中。

2. 使用 WHIP 广播

此广播脚本捕获本地媒体,将其作为仅发送(send-only)轨道添加到 RTCPeerConnection,并将生成的 SDP offer POST 到 WHIP URL。

从基本 HTML 页面开始,添加一个 <video> 元素以预览本地摄像头:

<video id="broadcast-preview" autoplay muted playsinline></video>

然后添加此脚本进行广播:

broadcast.jsjavascript
// Paste the webRTC.url value from your live input.
const WHIP_URL = "<WHIP_URL_FROM_YOUR_LIVE_INPUT>";

async function startBroadcast() {
    // 1. Capture the camera and microphone.
    const media = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true,
    });
    document.getElementById("broadcast-preview").srcObject = media;

    // 2. Create the peer connection and add each track as send-only.
    const pc = new RTCPeerConnection();
    media.getTracks().forEach((track) => {
        pc.addTransceiver(track, { direction: "sendonly" });
    });

    // 3. Create the SDP offer and set it as the local description.
    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);

    // 4. POST the offer to the WHIP endpoint.
    const response = await fetch(WHIP_URL, {
        method: "POST",
        headers: { "Content-Type": "application/sdp" },
        body: offer.sdp,
    });
    if (!response.ok) {
        throw new Error(`WHIP request failed: ${response.status}`);
    }

    // 5. Apply the SDP answer returned by Cloudflare.
    const answer = await response.text();
    await pc.setRemoteDescription({ type: "answer", sdp: answer });

    // The Location header identifies this session, used to stop it later.
    const sessionUrl = new URL(
        response.headers.get("Location"),
        WHIP_URL,
    ).toString();

    return { pc, sessionUrl };
}

startBroadcast().catch(console.error);

调用 startBroadcast() 并授予摄像头和麦克风权限后,浏览器会协商连接,并开始通过 WebRTC 向 Cloudflare 发送直播视频和音频。您无需选择编解码器——浏览器会自动协商受支持的编解码器。

此脚本不涵盖在多个摄像头或音频源之间选择,将使用浏览器提供的默认设备。

3. 使用 WHEP 回放

播放脚本是广播端的反向操作。它不添加本地轨道,而是添加仅接收(receive-only)transceiver,将 offer POST 到 WHEP URL,并将传入媒体附加到 <video> 元素。

从基本 HTML 页面开始,添加一个用于回放的 <video> 元素:

<video id="playback-video" autoplay playsinline controls></video>

然后添加此脚本进行播放:

playback.jsjavascript
// Paste the webRTCPlayback.url value from your live input.
const WHEP_URL = "<WHEP_URL_FROM_YOUR_LIVE_INPUT>";

async function startPlayback() {
    const pc = new RTCPeerConnection();

    // 1. Ask to receive one audio track and one video track.
    pc.addTransceiver("video", { direction: "recvonly" });
    pc.addTransceiver("audio", { direction: "recvonly" });

    // 2. Attach incoming media to the video element as it arrives.
    const stream = new MediaStream();
    document.getElementById("playback-video").srcObject = stream;
    pc.ontrack = (event) => stream.addTrack(event.track);

    // 3. Create the SDP offer and set it as the local description.
    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);

    // 4. POST the offer to the WHEP endpoint.
    const response = await fetch(WHEP_URL, {
        method: "POST",
        headers: { "Content-Type": "application/sdp" },
        body: offer.sdp,
    });
    if (!response.ok) {
        throw new Error(`WHEP request failed: ${response.status}`);
    }

    // 5. Apply the SDP answer returned by Cloudflare.
    const answer = await response.text();
    await pc.setRemoteDescription({ type: "answer", sdp: answer });

    const sessionUrl = new URL(
        response.headers.get("Location"),
        WHEP_URL,
    ).toString();

    return { pc, sessionUrl };
}

startPlayback().catch(console.error);

广播端在直播时,播放端会连接并以低于 500 毫秒的延迟显示该流。

4. 停止广播

页面关闭或连接断开时,WebRTC 会话会自动结束,但用户完成操作后仍应显式结束会话。向 Location 头中的会话 URL 发送 HTTP DELETE,然后关闭对等连接:

stop.jsjavascript
async function stop({ pc, sessionUrl }) {
    if (sessionUrl) {
        await fetch(sessionUrl, { method: "DELETE" });
    }
    pc.close();
}

这同时适用于 WHIP 和 WHEP 会话——传入 startBroadcast() 或 startPlayback() 返回的对象即可。

5. 完整可运行示例

以下单文件合并了上文全部内容。将两个占位 URL 替换为直播输入中的 webRTC.url 和 webRTCPlayback.url 值。然后通过 https(使用 Workers 或 Pages)或 localhost 提供该文件,并在浏览器中打开。

index.htmlhtml
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Cloudflare Stream WHIP/WHEP example</title>
    </head>
    <body>
        <h2>Broadcast (WHIP)</h2>
        <video id="broadcast-preview" autoplay muted playsinline></video>
        <button id="broadcast-btn">Start broadcasting</button>

        <h2>Playback (WHEP)</h2>
        <video id="playback-video" autoplay playsinline controls></video>
        <button id="playback-btn">Start playback</button>

        <script type="module">
            const WHIP_URL = "<WHIP_URL_FROM_YOUR_LIVE_INPUT>";
            const WHEP_URL = "<WHEP_URL_FROM_YOUR_LIVE_INPUT>";

            async function negotiate(pc, url) {
                const offer = await pc.createOffer();
                await pc.setLocalDescription(offer);

                const response = await fetch(url, {
                    method: "POST",
                    headers: { "Content-Type": "application/sdp" },
                    body: offer.sdp,
                });
                if (!response.ok) {
                    throw new Error(`Request failed: ${response.status}`);
                }

                const answer = await response.text();
                await pc.setRemoteDescription({ type: "answer", sdp: answer });
                return new URL(response.headers.get("Location"), url).toString();
            }

            document
                .getElementById("broadcast-btn")
                .addEventListener("click", async () => {
                    const media = await navigator.mediaDevices.getUserMedia({
                        video: true,
                        audio: true,
                    });
                    document.getElementById("broadcast-preview").srcObject = media;

                    const pc = new RTCPeerConnection();
                    media
                        .getTracks()
                        .forEach((track) =>
                            pc.addTransceiver(track, { direction: "sendonly" }),
                        );

                    await negotiate(pc, WHIP_URL);
                });

            document
                .getElementById("playback-btn")
                .addEventListener("click", async () => {
                    const pc = new RTCPeerConnection();
                    pc.addTransceiver("video", { direction: "recvonly" });
                    pc.addTransceiver("audio", { direction: "recvonly" });

                    const stream = new MediaStream();
                    document.getElementById("playback-video").srcObject = stream;
                    pc.ontrack = (event) => stream.addTrack(event.track);

                    await negotiate(pc, WHEP_URL);
                });
        </script>
    </body>
</html>

调试

如果广播或播放会话无法连接,浏览器内置的 WebRTC 工具会显示 SDP 交换和 ICE 连接状态:

  • Chrome:导航至 chrome://webrtc-internals 查看详细日志和图表。
  • Firefox:导航至 about:webrtc 查看 WebRTC 会话信息。
  • Safari:在检查器中打开设置选项卡(齿轮图标),在下拉菜单中将 WebRTC logging 设为 "Verbose"。

常见问题:

  • getUserMedia 抛出错误或未返回任何内容 — 确认页面通过安全方式提供,并且您已授予摄像头和麦克风权限。
  • POST 失败 — 确认粘贴了正确的 URL。广播使用 webRTC.url,播放使用 webRTCPlayback.url。
  • 播放画面一直为黑 — 确认同一输入上有广播端正在直播,且未启用 signed URLs。

后续步骤

这篇文档对您有帮助吗?