Room.vue 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <template>
  2. <div class="room">
  3. <label>房间号:{{roomId}}({{roomStatus}})</label>
  4. <p>当前选中的流:{{selectedStreamStatus}}</p>
  5. <h3>本地(发布)流</h3>
  6. <MediaPlayer v-for="stream in localStreams" :key="stream.sid" className="local-stream" v-bind:client="client" v-bind:stream="stream" v-bind:onClick="handleSelectStream"/>
  7. <h3>远端(订阅)流</h3>
  8. <MediaPlayer v-for="stream in remoteStreams" :key="stream.sid" className="remote-stream" v-bind:client="client" v-bind:stream="stream" v-bind:onClick="handleSelectStream"/>
  9. <h3>操作</h3>
  10. <button v-on:click="handleJoinRoom">加入房间</button>
  11. <button v-on:click="handlePublish">发布</button>
  12. <button v-on:click="handlePublishScreen">屏幕共享</button>
  13. <button v-on:click="handleUnpublish">取消发布/屏幕共享</button>
  14. <button v-on:click="handleSubscribe">订阅</button>
  15. <button v-on:click="handleUnsubscribe">取消订阅</button>
  16. <button v-on:click="handleLeaveRoom">离开房间</button>
  17. </div>
  18. </template>
  19. <script>
  20. import sdk, { Client } from 'urtc-sdk';
  21. import config from '../config';
  22. import MediaPlayer from '../components/MediaPlayer.vue';
  23. const { AppId, AppKey } = config;
  24. // 此处使用固定的房间号的随机的用户ID,请自行替换
  25. const RoomId = 'ssss02';
  26. const UserId = Math.floor(Math.random() * 1000000).toString();
  27. console.log('UCloudRTC sdk version: ', sdk.version);
  28. export default {
  29. name: 'Room',
  30. components: {
  31. MediaPlayer
  32. },
  33. data: function () {
  34. return {
  35. roomId: RoomId,
  36. userId: UserId,
  37. isJoinedRoom: false,
  38. selectedStream: null,
  39. localStreams: [],
  40. remoteStreams: []
  41. };
  42. },
  43. computed: {
  44. roomStatus: function () {
  45. return this.isJoinedRoom ? '已加入' : '未加入';
  46. },
  47. selectedStreamStatus: function () {
  48. return this.selectedStream ? this.selectedStream.sid : '未选择';
  49. }
  50. },
  51. created: function () {
  52. if (!AppId || !AppKey) {
  53. alert('请先设置 AppId 和 AppKey');
  54. return;
  55. }
  56. if (!RoomId) {
  57. alert('请先设置 RoomId');
  58. return;
  59. }
  60. if (!UserId) {
  61. alert('请先设置 UserId');
  62. }
  63. },
  64. mounted: function () {
  65. const token = sdk.generateToken(AppId, AppKey, RoomId, UserId);
  66. this.client = new Client(AppId, token);
  67. this.client.on('stream-published', (localStream) => {
  68. console.info('stream-published: ', localStream);
  69. const { localStreams } = this;
  70. localStreams.push(localStream);
  71. });
  72. this.client.on('stream-added', (remoteStream) => {
  73. console.info('stream-added: ', remoteStream);
  74. const { remoteStreams } = this;
  75. remoteStreams.push(remoteStream);
  76. // 自动订阅
  77. this.client.subscribe(remoteStream.sid, (err) => {
  78. console.error('自动订阅失败:', err);
  79. });
  80. });
  81. this.client.on('stream-subscribed', (remoteStream) => {
  82. console.info('stream-subscribed: ', remoteStream);
  83. const { remoteStreams } = this;
  84. const idx = remoteStreams.findIndex(item => item.sid === remoteStream.sid);
  85. if (idx >= 0) {
  86. remoteStreams.splice(idx, 1, remoteStream);
  87. }
  88. });
  89. this.client.on('stream-removed', (remoteStream) => {
  90. console.info('stream-removed: ', remoteStream);
  91. const { remoteStreams } = this;
  92. const idx = remoteStreams.findIndex(item => item.sid === remoteStream.sid);
  93. if (idx >= 0) {
  94. remoteStreams.splice(idx, 1);
  95. }
  96. });
  97. this.client.on('connection-state-change', ({ previous, current }) => {
  98. console.log(`连接状态 ${previous} -> ${current}`);
  99. });
  100. this.client.on('stream-reconnected', ({ previous, current }) => {
  101. console.log(`流已断开重连`);
  102. const isLocalStream = previous.type === 'publish';
  103. const streams = isLocalStream ? this.localStreams : this.remoteStreams;
  104. const idx = streams.findIndex(item => item.sid === previous.sid);
  105. if (idx >= 0) {
  106. // 更新流的信息
  107. streams.splice(idx, 1, current);
  108. }
  109. });
  110. window.addEventListener('beforeunload', this.handleLeaveRoom);
  111. },
  112. beforeDestroy: function () {
  113. console.info('component will destroy');
  114. window.removeEventListener('beforeunload', this.handleLeaveRoom);
  115. this.handleLeaveRoom();
  116. },
  117. destroyed: function () {
  118. this.isComponentDestroyed = true;
  119. },
  120. methods: {
  121. handleJoinRoom: function () {
  122. const { roomId, userId, isJoinedRoom } = this;
  123. if (isJoinedRoom) {
  124. alert('已经加入了房间');
  125. return;
  126. }
  127. if (!roomId) {
  128. alert('请先填写房间号');
  129. return;
  130. }
  131. this.client.joinRoom(roomId, userId, () => {
  132. console.info('加入房间成功');
  133. this.isJoinedRoom = true;
  134. }, (err) => {
  135. console.error('加入房间失败: ', err);
  136. });
  137. },
  138. handlePublish: function () {
  139. this.client.publish(err => {
  140. console.error(`发布失败:错误码 - ${err.name},错误信息 - ${err.message}`);
  141. });
  142. },
  143. handlePublishScreen: function () {
  144. this.client.publish({ audio: false, video: false, screen: true }, (err) => {
  145. console.error(`发布失败:错误码 - ${err.name},错误信息 - ${err.message}`);
  146. });
  147. },
  148. handleUnpublish: function () {
  149. const { selectedStream } = this;
  150. if (!selectedStream) {
  151. alert('未选择需要取消发布的本地流');
  152. return;
  153. }
  154. this.client.unpublish(selectedStream.sid, (stream) => {
  155. console.info('取消发布本地流成功:', stream);
  156. const { localStreams } = this;
  157. const idx = localStreams.findIndex(item => item.sid === stream.sid);
  158. if (idx >= 0) {
  159. localStreams.splice(idx, 1);
  160. }
  161. this.selectedStream = null;
  162. }, (err) => {
  163. console.error('取消发布本地流失败:', err);
  164. });
  165. },
  166. handleSubscribe: function () {
  167. const { selectedStream } = this;
  168. if (!selectedStream) {
  169. alert('未选择需要订阅的远端流');
  170. return;
  171. }
  172. this.client.subscribe(selectedStream.sid, (err) => {
  173. console.error('订阅失败:', err);
  174. });
  175. },
  176. handleUnsubscribe: function () {
  177. const { selectedStream } = this;
  178. if (!selectedStream) {
  179. alert('未选择需要取消订阅的远端流');
  180. return;
  181. }
  182. this.client.unsubscribe(selectedStream.sid, (stream) => {
  183. console.info('取消订阅成功:', stream);
  184. const { remoteStreams } = this;
  185. const idx = remoteStreams.findIndex(item => item.sid === stream.sid);
  186. if (idx >= 0) {
  187. remoteStreams.splice(idx, 1, stream);
  188. }
  189. }, (err) => {
  190. console.error('订阅失败:', err);
  191. });
  192. },
  193. handleLeaveRoom: function () {
  194. const { isJoinedRoom } = this;
  195. if (!isJoinedRoom) {
  196. return;
  197. }
  198. this.client.leaveRoom(() => {
  199. console.info('离开房间成功');
  200. this.selectedStream = null;
  201. this.localStreams = [];
  202. this.remoteStreams = [];
  203. this.isJoinedRoom = false;
  204. }, (err) => {
  205. console.error('离开房间失败:', err);
  206. });
  207. },
  208. handleSelectStream: function (stream) {
  209. console.log('select stream: ', stream);
  210. this.selectedStream = stream;
  211. }
  212. }
  213. };
  214. </script>
  215. <!-- Add "scoped" attribute to limit CSS to this component only -->
  216. <style>
  217. .room {
  218. max-width: 640px;
  219. margin: 0 auto;
  220. }
  221. .room .local-stream,
  222. .room .remote-stream {
  223. text-align: left;
  224. }
  225. .room button {
  226. padding: 8px 0;
  227. display: inline-block;
  228. width: 100%;
  229. border-width: 1px;
  230. border-radius: 6px;
  231. background-color: #fff;
  232. cursor: pointer;
  233. text-align: center;
  234. }
  235. .room input:visited,
  236. .room button:focus,
  237. .room button:visited,
  238. .room button:hover,
  239. .room button:active {
  240. outline: none;
  241. }
  242. </style>