index.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. <template>
  2. <div class="pull-wrap">
  3. <template v-if="roomNoLive">当前房间没在直播~</template>
  4. <template v-else>
  5. <div class="left">
  6. <div
  7. ref="topRef"
  8. class="head"
  9. >
  10. <div class="info">
  11. <div class="avatar"></div>
  12. <div class="detail">
  13. <div class="top">房间号:{{ route.params.roomId }}</div>
  14. <div class="bottom">
  15. <span>你的socketId:{{ getSocketId() }}</span>
  16. </div>
  17. </div>
  18. </div>
  19. </div>
  20. <div class="video-wrap">
  21. <video
  22. id="localVideo"
  23. ref="localVideoRef"
  24. autoplay
  25. webkit-playsinline="true"
  26. playsinline
  27. x-webkit-airplay="allow"
  28. x5-video-player-type="h5"
  29. x5-video-player-fullscreen="true"
  30. x5-video-orientation="portraint"
  31. muted
  32. controls
  33. ></video>
  34. </div>
  35. <div
  36. ref="bottomRef"
  37. class="gift"
  38. >
  39. <div
  40. v-for="(item, index) in giftList"
  41. :key="index"
  42. class="item"
  43. >
  44. <div class="ico"></div>
  45. <div class="name">{{ item.name }}</div>
  46. <div class="price">{{ item.price }}</div>
  47. </div>
  48. </div>
  49. </div>
  50. <div class="right">
  51. <div class="tab">
  52. <span>在线用户</span>
  53. <span> | </span>
  54. <span>大航海</span>
  55. </div>
  56. <div class="user-list">
  57. <div
  58. v-for="(item, index) in liveUserList"
  59. :key="index"
  60. class="item"
  61. >
  62. <div class="info">
  63. <div class="avatar"></div>
  64. <div class="nickname">{{ item.socketId }}</div>
  65. </div>
  66. <div class="expr">{{ item.expr }}</div>
  67. </div>
  68. </div>
  69. <div class="danmu-list">
  70. <div
  71. v-for="(item, index) in damuList"
  72. :key="index"
  73. class="item"
  74. >
  75. <span class="name">{{ item.socketId }}:</span>
  76. <span class="msg">{{ item.msg }}</span>
  77. </div>
  78. </div>
  79. <div class="send-msg">
  80. <textarea
  81. v-model="danmuStr"
  82. class="ipt"
  83. ></textarea>
  84. <div
  85. class="btn"
  86. @click="sendDanmu"
  87. >
  88. 发送
  89. </div>
  90. </div>
  91. </div>
  92. </template>
  93. </div>
  94. </template>
  95. <script lang="ts" setup>
  96. import { onMounted, onUnmounted, ref } from 'vue';
  97. import { useRoute } from 'vue-router';
  98. import { IAdminIn, ICandidate, IOffer } from '@/interface';
  99. import { WebRTCClass } from '@/network/webRtc';
  100. import {
  101. WebSocketClass,
  102. WsConnectStatusEnum,
  103. WsMsgTypeEnum,
  104. } from '@/network/webSocket';
  105. import { useNetworkStore } from '@/store/network';
  106. const networkStore = useNetworkStore();
  107. const route = useRoute();
  108. const danmuStr = ref('');
  109. const topRef = ref<HTMLDivElement>();
  110. const bottomRef = ref<HTMLDivElement>();
  111. const roomNoLive = ref(false);
  112. const isAddTrack = ref(false);
  113. const roomIdRef = ref<HTMLInputElement>();
  114. const joinRef = ref<HTMLButtonElement>();
  115. const leaveRef = ref<HTMLButtonElement>();
  116. const roomId = ref('');
  117. const websocketInstant = ref<WebSocketClass>();
  118. const isDone = ref(false);
  119. const localVideoRef = ref<HTMLVideoElement>();
  120. const localStream = ref();
  121. const joined = ref(false);
  122. const offerSended = ref(new Set());
  123. const giftList = ref([
  124. { name: '鲜花', ico: '', price: '免费' },
  125. { name: '肥宅水', ico: '', price: '2元' },
  126. { name: '小鸡腿', ico: '', price: '3元' },
  127. { name: '大鸡腿', ico: '', price: '5元' },
  128. { name: '一杯咖啡', ico: '', price: '10元' },
  129. ]);
  130. const damuList = ref<
  131. {
  132. socketId: string;
  133. msgType: number;
  134. msg: string;
  135. }[]
  136. >([]);
  137. const liveUserList = ref<
  138. {
  139. socketId: string;
  140. avatar: string;
  141. expr: number;
  142. }[]
  143. >([]);
  144. function closeWs() {
  145. const instance = networkStore.wsMap.get(roomId.value);
  146. if (!instance) return;
  147. instance.close();
  148. }
  149. function sendDanmu() {
  150. if (!danmuStr.value.length) {
  151. alert('请输入弹幕内容!');
  152. }
  153. if (!websocketInstant.value) return;
  154. websocketInstant.value.send({
  155. msgType: WsMsgTypeEnum.message,
  156. data: { msg: danmuStr.value },
  157. });
  158. damuList.value.push({
  159. socketId: getSocketId(),
  160. msgType: 1,
  161. msg: danmuStr.value,
  162. });
  163. danmuStr.value = '';
  164. }
  165. onUnmounted(() => {
  166. closeWs();
  167. });
  168. onMounted(() => {
  169. if (topRef.value && bottomRef.value && localVideoRef.value) {
  170. const res =
  171. bottomRef.value.getBoundingClientRect().top -
  172. (topRef.value.getBoundingClientRect().top +
  173. topRef.value.getBoundingClientRect().height);
  174. localVideoRef.value.style.height = `${res}px`;
  175. }
  176. roomId.value = route.params.roomId as string;
  177. console.warn('开始new WebSocketClass');
  178. websocketInstant.value = new WebSocketClass({
  179. roomId: roomId.value,
  180. url:
  181. process.env.NODE_ENV === 'development'
  182. ? 'ws://localhost:4300'
  183. : 'wss://live.hsslive.cn',
  184. isAdmin: false,
  185. });
  186. websocketInstant.value.update();
  187. initReceive();
  188. sendJoin();
  189. localVideoRef.value?.addEventListener('loadstart', () => {
  190. console.warn('视频流-loadstart');
  191. const rtc = networkStore.getRtcMap(roomId.value);
  192. if (!rtc) return;
  193. rtc.rtcStatus.loadstart = true;
  194. rtc.update();
  195. });
  196. localVideoRef.value?.addEventListener('loadedmetadata', () => {
  197. console.warn('视频流-loadedmetadata');
  198. const rtc = networkStore.getRtcMap(roomId.value);
  199. if (!rtc) return;
  200. rtc.rtcStatus.loadedmetadata = true;
  201. rtc.update();
  202. batchSendOffer();
  203. });
  204. });
  205. function getSocketId() {
  206. return networkStore.wsMap.get(roomId.value!)?.socketIo?.id || '-1';
  207. }
  208. function sendJoin() {
  209. const instance = networkStore.wsMap.get(roomId.value);
  210. if (!instance) return;
  211. instance.send({ msgType: WsMsgTypeEnum.join, data: {} });
  212. }
  213. function batchSendOffer() {
  214. liveUserList.value.forEach(async (item) => {
  215. if (
  216. !offerSended.value.has(item.socketId) &&
  217. item.socketId !== getSocketId()
  218. ) {
  219. await startNewWebRtc(item.socketId);
  220. await addTrack();
  221. console.warn('new WebRTCClass完成');
  222. console.log('执行sendOffer', {
  223. sender: getSocketId(),
  224. receiver: item.socketId,
  225. });
  226. sendOffer({ sender: getSocketId(), receiver: item.socketId });
  227. offerSended.value.add(item.socketId);
  228. }
  229. });
  230. }
  231. function closeRtc() {
  232. networkStore.rtcMap.forEach((rtc) => {
  233. rtc.close();
  234. });
  235. }
  236. function initReceive() {
  237. const instance = websocketInstant.value;
  238. if (!instance?.socketIo) return;
  239. // websocket连接成功
  240. instance.socketIo.on(WsConnectStatusEnum.connect, () => {
  241. console.log('【websocket】websocket连接成功', instance.socketIo?.id);
  242. if (!instance) return;
  243. instance.status = WsConnectStatusEnum.connect;
  244. instance.update();
  245. });
  246. // websocket连接断开
  247. instance.socketIo.on(WsConnectStatusEnum.disconnect, () => {
  248. console.log('【websocket】websocket连接断开', instance);
  249. if (!instance) return;
  250. instance.status = WsConnectStatusEnum.disconnect;
  251. instance.update();
  252. });
  253. // 当前所有在线用户
  254. instance.socketIo.on(WsMsgTypeEnum.roomLiveing, (data: IAdminIn) => {
  255. console.log('【websocket】收到管理员正在直播', data);
  256. });
  257. // 当前所有在线用户
  258. instance.socketIo.on(WsMsgTypeEnum.roomNoLive, (data: IAdminIn) => {
  259. console.log('【websocket】收到管理员不在直播', data);
  260. roomNoLive.value = true;
  261. closeRtc();
  262. });
  263. // 当前所有在线用户
  264. instance.socketIo.on(WsMsgTypeEnum.liveUser, (data) => {
  265. console.log('【websocket】当前所有在线用户', data);
  266. if (!instance) return;
  267. liveUserList.value = data.map((item) => ({
  268. avatar: 'red',
  269. socketId: item.id,
  270. expr: 1,
  271. }));
  272. });
  273. // 收到offer
  274. instance.socketIo.on(WsMsgTypeEnum.offer, async (data: IOffer) => {
  275. console.warn('【websocket】收到offer', data);
  276. if (!instance) return;
  277. if (data.data.receiver === getSocketId()) {
  278. console.log('收到offer,这个offer是发给我的');
  279. const rtc = startNewWebRtc(data.data.sender);
  280. await rtc.setRemoteDescription(data.data.sdp);
  281. const sdp = await rtc.createAnswer();
  282. await rtc.setLocalDescription(sdp);
  283. websocketInstant.value?.send({
  284. msgType: WsMsgTypeEnum.answer,
  285. data: { sdp, sender: getSocketId(), receiver: data.data.sender },
  286. });
  287. } else {
  288. console.log('收到offer,但是这个offer不是发给我的');
  289. }
  290. });
  291. // 收到answer
  292. instance.socketIo.on(WsMsgTypeEnum.answer, async (data: IOffer) => {
  293. console.warn('【websocket】收到answer', data);
  294. if (isDone.value) return;
  295. if (!instance) return;
  296. const rtc = networkStore.getRtcMap(`${roomId.value}___${data.socketId}`);
  297. console.log(rtc, '收到answer收到answer');
  298. if (!rtc) return;
  299. rtc.rtcStatus.answer = true;
  300. rtc.update();
  301. if (data.data.receiver === getSocketId()) {
  302. console.log('收到answer,这个answer是发给我的');
  303. await rtc.setRemoteDescription(data.data.sdp);
  304. } else {
  305. console.log('收到answer,但这个answer不是发给我的');
  306. }
  307. });
  308. // 收到candidate
  309. instance.socketIo.on(WsMsgTypeEnum.candidate, (data: ICandidate) => {
  310. console.warn('【websocket】收到candidate', data);
  311. if (isDone.value) return;
  312. if (!instance) return;
  313. const rtc =
  314. networkStore.getRtcMap(`${roomId.value}___${data.socketId}`) ||
  315. networkStore.getRtcMap(roomId.value);
  316. if (!rtc) return;
  317. if (data.socketId !== getSocketId()) {
  318. console.log('不是我发的candidate');
  319. const candidate = new RTCIceCandidate({
  320. sdpMid: data.data.sdpMid,
  321. sdpMLineIndex: data.data.sdpMLineIndex,
  322. candidate: data.data.candidate,
  323. });
  324. rtc.peerConnection
  325. ?.addIceCandidate(candidate)
  326. .then(() => {
  327. console.log('candidate成功');
  328. })
  329. .catch((err) => {
  330. console.error('candidate失败', err);
  331. });
  332. } else {
  333. console.log('是我发的candidate');
  334. }
  335. });
  336. // 收到用户发送消息
  337. instance.socketIo.on(WsMsgTypeEnum.message, (data) => {
  338. console.log('【websocket】收到用户发送消息', data);
  339. if (!instance) return;
  340. damuList.value.push({
  341. socketId: data.socketId,
  342. msgType: 1,
  343. msg: data.data.msg,
  344. });
  345. });
  346. // 用户加入房间完成
  347. instance.socketIo.on(WsMsgTypeEnum.joined, (data) => {
  348. console.log('【websocket】用户加入房间完成', data);
  349. joined.value = true;
  350. });
  351. // 其他用户加入房间
  352. instance.socketIo.on(WsMsgTypeEnum.otherJoin, (data) => {
  353. console.log('【websocket】其他用户加入房间', data);
  354. if (joined.value) {
  355. batchSendOffer();
  356. }
  357. });
  358. // 用户离开房间
  359. instance.socketIo.on(WsMsgTypeEnum.leave, (data) => {
  360. console.log('【websocket】用户离开房间', data);
  361. if (!instance) return;
  362. instance.socketIo?.emit(WsMsgTypeEnum.leave, {
  363. roomId: instance.roomId,
  364. });
  365. });
  366. // 用户离开房间完成
  367. instance.socketIo.on(WsMsgTypeEnum.leaved, (data) => {
  368. console.log('【websocket】用户离开房间完成', data);
  369. if (!instance) return;
  370. const res = liveUserList.value.filter(
  371. (item) => item.socketId !== data.socketId
  372. );
  373. liveUserList.value = res;
  374. console.log('当前所有在线用户', JSON.stringify(res));
  375. });
  376. }
  377. function addTrack() {
  378. if (!localStream.value) return;
  379. liveUserList.value.forEach((item) => {
  380. if (item.socketId !== getSocketId()) {
  381. localStream.value.getTracks().forEach((track) => {
  382. const rtc = networkStore.getRtcMap(
  383. `${roomId.value}___${item.socketId}`
  384. );
  385. rtc?.addTrack(track, localStream.value);
  386. });
  387. }
  388. });
  389. isAddTrack.value = true;
  390. }
  391. async function sendOffer({
  392. sender,
  393. receiver,
  394. }: {
  395. sender: string;
  396. receiver: string;
  397. }) {
  398. if (isDone.value) return;
  399. if (!websocketInstant.value) return;
  400. const rtc = networkStore.getRtcMap(`${roomId.value}___${receiver}`);
  401. if (!rtc) return;
  402. const sdp = await rtc.createOffer();
  403. await rtc.setLocalDescription(sdp);
  404. websocketInstant.value.send({
  405. msgType: WsMsgTypeEnum.offer,
  406. data: { sdp, sender, receiver },
  407. });
  408. }
  409. function startNewWebRtc(receiver: string) {
  410. console.warn('开始new WebRTCClass', receiver);
  411. const rtc = new WebRTCClass({ roomId: `${roomId.value}___${receiver}` });
  412. rtc.rtcStatus.joined = true;
  413. rtc.update();
  414. return rtc;
  415. }
  416. </script>
  417. <style lang="scss" scoped>
  418. .pull-wrap {
  419. margin: 20px auto 0;
  420. min-width: $large-width;
  421. height: 700px;
  422. text-align: center;
  423. .left {
  424. position: relative;
  425. display: inline-block;
  426. box-sizing: border-box;
  427. width: $large-left-width;
  428. height: 100%;
  429. border: 1px solid red;
  430. border-radius: 10px;
  431. background-color: white;
  432. color: #9499a0;
  433. vertical-align: top;
  434. .head {
  435. display: flex;
  436. justify-content: space-between;
  437. padding: 20px;
  438. background-color: pink;
  439. .tag {
  440. display: inline-block;
  441. margin-right: 5px;
  442. padding: 1px 4px;
  443. border: 1px solid;
  444. border-radius: 2px;
  445. color: #9499a0;
  446. font-size: 12px;
  447. }
  448. .info {
  449. display: flex;
  450. align-items: center;
  451. text-align: initial;
  452. .avatar {
  453. margin-right: 20px;
  454. width: 64px;
  455. height: 64px;
  456. border-radius: 50%;
  457. background-color: yellow;
  458. }
  459. .detail {
  460. .top {
  461. margin-bottom: 10px;
  462. color: #18191c;
  463. }
  464. .bottom {
  465. font-size: 14px;
  466. }
  467. }
  468. }
  469. .other {
  470. display: flex;
  471. flex-direction: column;
  472. justify-content: center;
  473. font-size: 12px;
  474. .top {
  475. display: flex;
  476. align-items: center;
  477. .item {
  478. display: flex;
  479. align-items: center;
  480. margin-right: 20px;
  481. .ico {
  482. display: inline-block;
  483. margin-right: 4px;
  484. width: 10px;
  485. height: 10px;
  486. border-radius: 50%;
  487. background-color: skyblue;
  488. }
  489. }
  490. }
  491. .bottom {
  492. margin-top: 10px;
  493. }
  494. }
  495. }
  496. .video-wrap {
  497. // height: 100px;
  498. // height: 550px;
  499. background-color: #18191c;
  500. #localVideo {
  501. max-width: 100%;
  502. max-height: 100%;
  503. }
  504. }
  505. .gift {
  506. position: absolute;
  507. right: 0;
  508. bottom: 0;
  509. left: 0;
  510. display: flex;
  511. align-items: center;
  512. justify-content: space-around;
  513. height: 100px;
  514. background-color: yellow;
  515. .item {
  516. margin-right: 10px;
  517. text-align: center;
  518. .ico {
  519. width: 50px;
  520. height: 50px;
  521. background-color: skyblue;
  522. }
  523. .name {
  524. color: #18191c;
  525. font-size: 12px;
  526. }
  527. .price {
  528. color: #9499a0;
  529. font-size: 12px;
  530. }
  531. }
  532. }
  533. }
  534. .right {
  535. position: relative;
  536. display: inline-block;
  537. box-sizing: border-box;
  538. box-sizing: border-box;
  539. margin-left: 10px;
  540. min-width: 300px;
  541. height: 100%;
  542. border: 1px solid red;
  543. border-radius: 10px;
  544. background-color: white;
  545. color: #9499a0;
  546. .tab {
  547. display: flex;
  548. align-items: center;
  549. justify-content: space-evenly;
  550. padding: 5px 0;
  551. font-size: 12px;
  552. }
  553. .user-list {
  554. overflow-y: scroll;
  555. padding: 0 15px;
  556. height: 100px;
  557. background-color: pink;
  558. .item {
  559. display: flex;
  560. align-items: center;
  561. justify-content: space-between;
  562. margin-bottom: 10px;
  563. font-size: 12px;
  564. .info {
  565. display: flex;
  566. align-items: center;
  567. .avatar {
  568. margin-right: 5px;
  569. width: 25px;
  570. height: 25px;
  571. border-radius: 50%;
  572. background-color: skyblue;
  573. }
  574. .nickname {
  575. color: black;
  576. }
  577. }
  578. }
  579. }
  580. .danmu-list {
  581. overflow-y: scroll;
  582. padding: 0 15px;
  583. height: 350px;
  584. text-align: initial;
  585. .item {
  586. margin-bottom: 10px;
  587. font-size: 12px;
  588. .name {
  589. color: #9499a0;
  590. }
  591. .msg {
  592. color: #61666d;
  593. }
  594. }
  595. }
  596. .send-msg {
  597. position: absolute;
  598. bottom: 15px;
  599. box-sizing: border-box;
  600. padding: 0 10px;
  601. width: 100%;
  602. .ipt {
  603. display: block;
  604. box-sizing: border-box;
  605. margin: 0 auto;
  606. padding: 10px;
  607. width: 100%;
  608. height: 60px;
  609. outline: none;
  610. border: 1px solid hsla(0, 0%, 60%, 0.2);
  611. border-radius: 4px;
  612. background-color: #f1f2f3;
  613. font-size: 14px;
  614. }
  615. .btn {
  616. box-sizing: border-box;
  617. margin-top: 10px;
  618. margin-left: auto;
  619. padding: 5px;
  620. width: 80px;
  621. border-radius: 4px;
  622. background-color: #23ade5;
  623. color: white;
  624. text-align: center;
  625. font-size: 12px;
  626. }
  627. }
  628. }
  629. }
  630. // 屏幕宽度小于$large-width的时候
  631. @media screen and (max-width: $large-width) {
  632. .pull-wrap {
  633. .left {
  634. width: $medium-left-width;
  635. }
  636. .right {
  637. .list {
  638. .item {
  639. width: 150px;
  640. height: 80px;
  641. }
  642. }
  643. }
  644. }
  645. }
  646. </style>