十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Cloudflare Stream 直播推流 API 实战:Live Input 创建、状态监测、Simulcast 与 WebRTC(WHIP/WHEP)

Cloudflare Stream 直播推流 API 实战:Live Input 创建、状态监测、Simulcast 与 WebRTC(WHIP/WHEP) Cloudflare Stream 直播推流 API 实战Live Input 创建、状态监测、Simulcast 与 WebRTCWHIP/WHEP【免费下载链接】skillsSkills Catalog for Codex项目地址: https://gitcode.com/GitHub_Trending/skills4/skills本篇技术指南聚焦 Cloudflare Stream 的直播Live Streaming能力完整讲解如何创建直播输入Live Input、查询直播状态、配置多平台 Simulcast 推流如 YouTube、Twitch以及如何用 WebRTCWHIP/WHEP实现浏览器直接推流与播放。读完本文你将掌握基于 Cloudflare SDK 与原生 fetch API 两套调用方式能够在 Cloudflare Workers 中构建一条从直播接入、自动录制到多平台分发的完整直播链路。直播链路核心概念Cloudflare Stream 是构建在 Cloudflare 全球网络上的 Serverless 视频平台直播能力包含三大核心环节直播输入Live Input为一路直播创建一个接入点返回 RTMPS、SRT、WebRTC 三种推流入口信息直播输出Live Outputs即 Simulcast将一路直播同时转发到多个外部平台YouTube、Twitch 等或自定义 RTMP 目标录制Recording直播结束后自动转码为点播VOD沿用 Cloudflare Stream 点播 API 中的播放、签名 URL 等能力。这一编排逻辑与仓库中 cloudflare-deploy 技能 的定位一致该技能聚合了 Cloudflare 平台各产品的部署参考其中 Stream 参考文档 将 api-live.md即本文主体列为直播场景的核心阅读材料。创建 Live Input创建 Live Input 是整个直播流程的起点。创建成功后Cloudflare 会为这一路直播分配全局唯一的uid并返回三套推流地址RTMPSrtmps.urlstreamKey、SRTsrt.urlsrt.streamIdsrt.passphrase以及 WebRTC 入口webRTC。方式一使用 Cloudflare SDK推荐import Cloudflare from cloudflare; const client new Cloudflare({ apiToken: env.CF_API_TOKEN }); const liveInput await client.stream.liveInputs.create({ account_id: env.CF_ACCOUNT_ID, recording: { mode: automatic, timeoutSeconds: 30 }, deleteRecordingAfterDays: 30 }); // Returns: { uid, rtmps, srt, webRTC }关键参数说明account_id/apiToken账号标识与 API Token对应 configuration.md 中的环境变量CF_ACCOUNT_ID与CF_API_TOKEN。Token 仅应存放在后端切勿暴露在前端代码中详见 gotchas.md 安全清单recording.mode录制模式automatic表示自动录制所有直播详见下文「录制设置」recording.timeoutSeconds直播结束后等待 N 秒无活动即停止录制deleteRecordingAfterDays录制生成的 VOD 在 N 天后自动删除。方式二Raw fetch API无 SDK 依赖在 Cloudflare Workers 或任意服务端环境中也可以直接用原生fetch调用 REST APIasync function createLiveInput(accountId: string, apiToken: string) { const response await fetch( https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/live_inputs, { method: POST, headers: { Authorization: Bearer ${apiToken}, Content-Type: application/json }, body: JSON.stringify({ recording: { mode: automatic, timeoutSeconds: 30 }, deleteRecordingAfterDays: 30 }) } ); const { result } await response.json(); return { uid: result.uid, rtmps: { url: result.rtmps.url, streamKey: result.rtmps.streamKey }, srt: { url: result.srt.url, streamId: result.srt.streamId, passphrase: result.srt.passphrase }, webRTC: result.webRTC }; }创建成功后将rtmps.url与streamKey填入 OBS / FFmpeg 等推流工具即可开始推流。若直播无法连接优先检查是否使用了 API 返回的精确 URL 与密钥并确认防火墙放行出站 443 端口见 gotchas.md 的排障清单。检查直播状态通过 GET 请求live_inputs/{live_input_id}可实时查询直播状态核心判断依据是status.current.state是否等于connectedasync function getLiveStatus(accountId: string, liveInputId: string, apiToken: string) { const response await fetch( https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/live_inputs/${liveInputId}, { headers: { Authorization: Bearer ${apiToken} } } ); const { result } await response.json(); return { isLive: result.status?.current?.state connected, recording: result.recording, status: result.status }; }该接口同时返回recording与完整status对象可用于前端开播/未开播状态展示或作为直播监控服务的轮询依据。需要更高效率的状态变更通知时建议结合 Webhook 而非高频轮询——仓库 patterns.md 中给出了「Webhook 优先、轮询兜底」的完整工作流建议。Simulcast一路直播多平台分发SimulcastLive Outputs允许把一路直播同时转发到多个 RTMP 目标例如同时推送到 YouTube 与 Twitch从而避免在本地重复推流、节省上行带宽。需要留意的是每个 Live Input 的直播输出数量上限为 5 个见 gotchas.md 的 Limits 表。创建输出async function createLiveOutput( accountId: string, liveInputId: string, apiToken: string, outputUrl: string, streamKey: string ) { return fetch( https://api.cloudflare.com/client/v4/accounts/${accountId}/stream/live_inputs/${liveInputId}/outputs, { method: POST, headers: { Authorization: Bearer ${apiToken}, Content-Type: application/json }, body: JSON.stringify({ url: ${outputUrl}/${streamKey}, enabled: true, streamKey // For platforms like YouTube, Twitch }) } ).then(r r.json()); }参数说明url目标平台的 RTMP 地址拼接上你的平台 Stream Key例如rtmp://a.rtmp.youtube.com/live2/your-youtube-stream-keyenabled输出是否启用可用于临时暂停某个平台的转发streamKey目标平台YouTube、Twitch 等分配给你的 Stream Key。示例同时推送到 YouTube Twitchconst liveInput await createLiveInput(accountId, apiToken); // Add YouTube output await createLiveOutput( accountId, liveInput.uid, apiToken, rtmp://a.rtmp.youtube.com/live2, your-youtube-stream-key ); // Add Twitch output await createLiveOutput( accountId, liveInput.uid, apiToken, rtmp://live.twitch.tv/app, your-twitch-stream-key );WebRTC 直播浏览器直推与直播Cloudflare Stream 原生支持 WebRTC分别通过 WHIPWebRTC-HTTP Ingestion Protocol实现浏览器推流、WHEPWebRTC-HTTP Egress Protocol实现浏览器低延迟播放全程无需安装任何推流软件。Browser to StreamWHIP 推流async function startWebRTCBroadcast(liveInputId: string) { const pc new RTCPeerConnection(); // Add local media tracks const stream await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); stream.getTracks().forEach(track pc.addTrack(track, stream)); // Create offer const offer await pc.createOffer(); await pc.setLocalDescription(offer); // Send to Stream via WHIP const response await fetch( https://customer-CODE.cloudflarestream.com/${liveInputId}/webRTC/publish, { method: POST, headers: { Content-Type: application/sdp }, body: offer.sdp } ); const answer await response.text(); await pc.setRemoteDescription({ type: answer, sdp: answer }); }流程要点先用getUserMedia获取摄像头/麦克风轨道并加入RTCPeerConnection创建 SDP offer 后以application/sdp内容类型 POST 到 WHIP 发布端点/webRTC/publish再把服务端返回的 answer 设置到连接上即完成一次浏览器端直播发布。Stream to BrowserWHEP 播放async function playWebRTCStream(videoId: string) { const pc new RTCPeerConnection(); pc.addTransceiver(video, { direction: recvonly }); pc.addTransceiver(audio, { direction: recvonly }); const offer await pc.createOffer(); await pc.setLocalDescription(offer); const response await fetch( https://customer-CODE.cloudflarestream.com/${videoId}/webRTC/play, { method: POST, headers: { Content-Type: application/sdp }, body: offer.sdp } ); const answer await response.text(); await pc.setRemoteDescription({ type: answer, sdp: answer }); return pc; }播放侧使用recvonly方向的 transceiver 声明只接收不发送将 offer 提交到 WHEP 播放端点/webRTC/play设置 answer 后即可获得亚秒级低延迟播放。注意两个 URL 中的CODE是账号专属的 customer code对应 configuration.md 中的STREAM_CUSTOMER_CODE环境变量。录制设置直播自动转点播录制功能让直播结束即生成点播视频VOD自动沿用 点播 API 的播放、缩略图与签名 URL 能力。ModeBehaviorautomaticRecord all live streamsoffNo recordingtimeoutSecondsStop recording after N seconds of inactivity完整录制配置示例const recordingConfig { mode: automatic, timeoutSeconds: 30, // Auto-stop 30s after stream ends requireSignedURLs: true, // Require token for VOD playback allowedOrigins: [https://yourdomain.com] };配置解读timeoutSeconds: 30推流中断后 30 秒内未恢复即结束录制避免产生大量空白片段requireSignedURLs: true录制产物VOD必须携带签名 token 才能播放适合付费课程、私有直播回放等场景若开启该选项却未提供 token会出现「视频已上传但无法查看」的问题见 gotchas.md 排障项allowedOrigins域名白名单防止其他站点嵌入你的视频播放器防 hotlinking。若播放器出现无限加载优先检查你的域名是否已加入该数组对应 gotchas.md 的 CORS 排障项。服务端接入环境准备在将上述接口部署到 Cloudflare Workers 之前需要完成环境变量与密钥配置完整步骤见 configuration.md# Required CF_ACCOUNT_IDyour-account-id CF_API_TOKENyour-api-token # Customer subdomain (from dashboard) STREAM_CUSTOMER_CODEyour-customer-codeCF_API_TOKEN等敏感值应通过wrangler secret put CF_API_TOKEN写入 Secrets而非常量配置wrangler 配置示例 亦有覆盖。部署前可用npx wrangler whoami校验认证状态见 cloudflare-deploy 技能说明。常见问题与限制速查以下限制与排障要点来自 gotchas.md与直播场景强相关直播输出Simulcast数量上限每个 Live Input 最多 5 个输出直播无法连接多为 RTMPS URL 或 Stream Key 不正确使用 API 返回的精确值并确保出站 443 端口放行视频长时间处于inprogress大文件或复杂编码处理较慢最多等待约 5 分钟建议用 Webhook 替代轮询获取处理完成通知签名 URL 返回 403token 过期或签名无效检查过期时间戳与 JWK 是否正确、时钟是否同步直播安全建议启用requireSignedURLs保护私有内容、白名单allowedOrigins防盗链、为录制配置合理的保留天数deleteRecordingAfterDays。继续深入README.mdCloudflare Stream 总览与快速开始上传、播放器嵌入、Live Input 创建命令api.md点播视频的上传、播放、签名 URL、字幕与剪辑 APIconfiguration.mdSDK 安装、环境变量、Wrangler 配置、Webhook 与签名密钥设置patterns.md全栈上传流程、TUS 断点续传、JWT 自签名与 Webhook 校验最佳实践gotchas.md错误码、限额与排障清单workers 参考将上述直播 API 部署为 Worker 的完整实践。【免费下载链接】skillsSkills Catalog for Codex项目地址: https://gitcode.com/GitHub_Trending/skills4/skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表