vue项目实现网页在线直播,并实现录制直播,也可以理解为边录边传
以下为效果,左侧自己写的推流端,右侧为拉流端
资源准备
序号 | 资源名称 |
---|---|
1 | 云服务器 |
2 | 域名一个 |
一、安装srs流媒体服务器
宝塔网站管理这里点击设置添加上域名并设置SSL开启https
完成后进入管理面板获取推流地址
二、代码联调
<template> <div> <input type="text" v-model="webrtcUrl" placeholder="输入WebRTC URL" style="width: 100%" /> <button @click="startPublisherBtn">开始推流</button> <button @click="stopPublisherBtn">关闭推流</button> <video ref="pusher" autoplay :srcObject="stream" style="width: 100%; height: auto" /> </div></template><script>import Srs from "@/assets/js/srs.sdk";import { onMounted, ref, onUnmounted, nextTick } from "vue";export default { name: "webrtcPusher", setup() { const pusher = ref(null); // 使用 null 而不是 undefined const webrtcUrl = ref( "webrtc://live.abc.com/live/bkdbjf?secret=c447ab4e83884139907d7cbdaeaf9a6e" ); let rtcPublisher = null; // 用于存储RtcPublisher实例 let rtcPlayer = null; // 用于存储RtcPlayer实例 const startPublisher = async () => { try { rtcPublisher = new Srs.SrsRtcPublisherAsync(); // 创建RtcPublisher实例 const session = await rtcPublisher.publish(webrtcUrl.value); // 开始推流 console.log("推流成功", session); await nextTick(); // 等待DOM更新,确保pusher是可用的 // 如果需要,这里可以添加播放器的初始化代码(如果RtcPublisher也提供了流) } catch (error) { console.error("推流失败", error); // 如果RtcPublisher有close方法,调用它以关闭推流 if (rtcPublisher && rtcPublisher.close) { rtcPublisher.close(); } } }; const startPlayer = async () => { try { rtcPlayer = new Srs.SrsRtcPlayerAsync(); // 创建RtcPlayer实例 await rtcPlayer.play(webrtcUrl.value); // 开始播放 await nextTick(); // 等待DOM更新,确保pusher是可用的 // 设置视频源的srcObject if (rtcPlayer.stream && pusher.value) { pusher.value.srcObject = rtcPlayer.stream; } } catch (error) { console.error("播放失败", error); // 如果RtcPlayer有close或stop方法,调用它以停止播放 if (rtcPlayer && (rtcPlayer.close || rtcPlayer.stop)) { // 假设有一个close或stop方法可用 rtcPlayer.close?.() || rtcPlayer.stop?.(); } } }; const startPublisherBtn = async () => { await startPublisher(); await startPlayer(); }; const stopPublisherBtn = async () => { if (rtcPublisher && rtcPublisher.close) { rtcPublisher.close(); } if (rtcPlayer && (rtcPlayer.close || rtcPlayer.stop)) { rtcPlayer.close?.() || rtcPlayer.stop?.(); } }; onUnmounted(() => { // 组件卸载时关闭推流和播放 if (rtcPublisher && rtcPublisher.close) { rtcPublisher.close(); } if (rtcPlayer && (rtcPlayer.close || rtcPlayer.stop)) { rtcPlayer.close?.() || rtcPlayer.stop?.(); } }); return { pusher, webrtcUrl, startPublisherBtn, stopPublisherBtn }; },};</script><style scoped>.mirrored-video { transform: scaleX(-1); width: 100%; height: auto;}</style>
srs.sdk.js地址:点击获取
三、录制直播
开启录制即可