index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. window.onload = function () {
  2. const {
  3. AppId,
  4. AppKey
  5. } = window.config || {};
  6. // 此处使用固定的房间号的随机的用户ID,请自行替换
  7. const RoomId = "test";
  8. const UserId = Math.floor(Math.random() * 1000000).toString();
  9. if (!AppId || !AppKey) {
  10. alert('请先设置 AppId 和 AppKey');
  11. return;
  12. }
  13. if (!RoomId) {
  14. alert('请先设置 RoomId');
  15. return;
  16. }
  17. console.log('UCloudRTC sdk version:',UCloudRTC.version);
  18. const Player = function(client, stream, selectFunc) {
  19. this.client = client;
  20. this.stream = stream;
  21. this.element = document.createElement('div');
  22. // userId
  23. const uIDElem = document.createElement('div');
  24. uIDElem.innerHTML = `用户ID:${stream.uid}`;
  25. uIDElem.style = 'overflow: hidden; text-overflow: ellipsis;';
  26. this.element.appendChild(uIDElem);
  27. // streamId
  28. const sIDElem = document.createElement('div');
  29. sIDElem.innerHTML = `流ID:${stream.sid}`;
  30. sIDElem.style = 'overflow: hidden; text-overflow: ellipsis;';
  31. this.element.appendChild(sIDElem);
  32. // hint - unsubscribe
  33. const hintElem = document.createElement('p');
  34. hintElem.innerHTML = 'unsubscribe';
  35. hintElem.style = 'display: none;';
  36. this.hint = hintElem;
  37. this.element.appendChild(hintElem);
  38. // container
  39. const container = document.createElement('div');
  40. container.className = 'media-player';
  41. container.id = stream.sid;
  42. this.container = container;
  43. this.element.appendChild(container);
  44. this.handleSelect = function() {
  45. selectFunc(this.stream);
  46. }.bind(this);
  47. this.element.addEventListener('click', this.handleSelect);
  48. if (stream.mediaStream) {
  49. this.play();
  50. }
  51. }
  52. Player.prototype.play = function() {
  53. const isLocalStream = this.stream.type === 'publish';
  54. this.hint.style.display = 'none';
  55. this.container.style.display = 'inline-block';
  56. this.client.play({
  57. streamId: this.stream.sid,
  58. container: this.container,
  59. mirror: isLocalStream
  60. }, (err) => {
  61. if (err) {
  62. console.log(`自动播放失败 ${err}`);
  63. alert(`自动播放失败 ${err}`);
  64. }
  65. })
  66. }
  67. Player.prototype.stop = function() {
  68. const isLocalStream = this.stream.type === 'publish';
  69. this.container.style.display = 'none';
  70. if (!isLocalStream) {
  71. this.hint.style.display = 'block';
  72. }
  73. }
  74. Player.prototype.updateStream = function(stream) {
  75. this.stream = stream;
  76. if (stream.mediaStream) {
  77. this.play();
  78. } else {
  79. this.stop();
  80. }
  81. }
  82. Player.prototype.destroy = function() {
  83. this.element.removeEventListener('click', this.handleSelect);
  84. this.element.parentNode.removeChild(this.element);
  85. }
  86. // 用于维护应用内的状态
  87. const App = {
  88. state: {
  89. roomId: RoomId,
  90. userId: UserId,
  91. isJoinedRoom: false,
  92. selectedStream: null,
  93. localStreams: [],
  94. remoteStreams: [],
  95. players: [],
  96. },
  97. client: null,
  98. renderRoomId: function (roomId) {
  99. const roomElem = document.querySelector('#roomId');
  100. roomElem.innerHTML = roomId;
  101. },
  102. renderRoomStatus: function (status) {
  103. const roomStatusElem = document.querySelector('#roomStatus');
  104. if (status) {
  105. roomStatusElem.innerHTML = "已加入";
  106. } else {
  107. roomStatusElem.innerHTML = "未加入";
  108. }
  109. },
  110. renderSelectedStream: function (selectedStream) {
  111. const selectedStreamElem = document.querySelector('#selectedStream');
  112. if (selectedStream) {
  113. selectedStreamElem.innerHTML = selectedStream.sid;
  114. } else {
  115. selectedStreamElem.innerHTML = "未选择";
  116. }
  117. },
  118. renderStream: function (stream) {
  119. const isLocalStream = stream.type === 'publish';
  120. let parent;
  121. if (isLocalStream) {
  122. parent = document.querySelector('#pushers');
  123. } else {
  124. parent = document.querySelector('#pullers');
  125. }
  126. const player = new Player(this.client, stream, this.handleSelectStream.bind(this));
  127. // todo - handleSelectStream
  128. this.state.players.push(player);
  129. parent.appendChild(player.element);
  130. },
  131. unrenderStream: function (stream) {
  132. const idx = this.state.players.findIndex(item => item.stream.sid === stream.sid);
  133. if (idx < 0) {
  134. console.log('unrender stream - stream not found');
  135. return;
  136. }
  137. const player = this.state.players[idx];
  138. this.state.players.splice(idx, 1);
  139. player.destroy();
  140. },
  141. rerenderStream: function (stream) {
  142. const player = this.state.players.find(item => item.stream.sid === stream.sid);
  143. if (!player) {
  144. console.log('rerender stream - stream not found');
  145. return;
  146. }
  147. player.updateStream(stream);
  148. },
  149. init: function () {
  150. this.renderRoomId(RoomId);
  151. const token = UCloudRTC.generateToken(AppId, AppKey, RoomId, UserId);
  152. this.client = new UCloudRTC.Client(AppId, token);
  153. // 监听 publish 成功的事件
  154. this.client.on('stream-published', (localStream) => {
  155. console.info('stream-published: ', localStream);
  156. const { localStreams } = this.state;
  157. localStreams.push(localStream);
  158. this.renderStream(localStream);
  159. });
  160. this.client.on('stream-added', (remoteStream) => {
  161. console.info('stream-added: ', remoteStream);
  162. const { remoteStreams } = this.state;
  163. remoteStreams.push(remoteStream);
  164. this.renderStream(remoteStream);
  165. // 自动订阅
  166. this.client.subscribe(remoteStream.sid, (err) => {
  167. console.error('自动订阅失败:', err);
  168. });
  169. });
  170. this.client.on('stream-subscribed', (remoteStream) => {
  171. console.info('stream-subscribed: ', remoteStream);
  172. const { remoteStreams } = this.state;
  173. const idx = remoteStreams.findIndex(item => item.sid === remoteStream.sid);
  174. if (idx >= 0) {
  175. remoteStreams.splice(idx, 1, remoteStream);
  176. }
  177. this.rerenderStream(remoteStream);
  178. });
  179. this.client.on('stream-removed', (remoteStream) => {
  180. console.info('stream-removed: ', remoteStream);
  181. const { remoteStreams } = this.state;
  182. const idx = remoteStreams.findIndex(item => item.sid === remoteStream.sid);
  183. if (idx >= 0) {
  184. const p = remoteStreams[idx];
  185. remoteStreams.splice(idx, 1);
  186. this.unrenderStream(p);
  187. }
  188. });
  189. this.client.on('connection-state-change', ({ previous, current }) => {
  190. console.log(`连接状态 ${previous} -> ${current}`);
  191. });
  192. this.client.on('stream-reconnected', ({previous, current}) => {
  193. console.log(`流已断开重连`);
  194. const isLocalStream = previous.type === 'publish';
  195. const streams = isLocalStream ? this.state.localStreams : this.state.remoteStreams;
  196. const idx = streams.findIndex(item => item.sid === previous.sid);
  197. if (idx >= 0) {
  198. // 更新流的信息
  199. const oldStream = streams.splice(idx, 1, current)[0];
  200. this.unrenderStream(oldStream);
  201. streams.push(current);
  202. this.renderStream(current);
  203. }
  204. });
  205. document.querySelector('#joinRoomBtn').addEventListener('click', this.handleJoinRoom.bind(this));
  206. document.querySelector('#publishBtn').addEventListener('click', this.handlePublish.bind(this));
  207. document.querySelector('#publishScreenBtn').addEventListener('click', this.handlePublishScreen.bind(this));
  208. document.querySelector('#unPublishBtn').addEventListener('click', this.handleUnpublish.bind(this));
  209. document.querySelector('#subscribeBtn').addEventListener('click', this.handleSubscribe.bind(this));
  210. document.querySelector('#unSubscribeBtn').addEventListener('click', this.handleUnsubscribe.bind(this));
  211. document.querySelector('#leaveRoomBtn').addEventListener('click', this.handleLeaveRoom.bind(this));
  212. window.addEventListener('beforeunload', this.handleLeaveRoom.bind(this));
  213. },
  214. // 操作
  215. handleJoinRoom: function () {
  216. const {
  217. roomId,
  218. userId,
  219. isJoinedRoom
  220. } = this.state;
  221. if (isJoinedRoom) {
  222. alert('已经加入了房间');
  223. return;
  224. }
  225. if (!roomId) {
  226. alert('请先填写房间号');
  227. return;
  228. }
  229. this.client.joinRoom(roomId, userId, () => {
  230. console.info('加入房间成功');
  231. this.state.isJoinedRoom = true
  232. this.renderRoomStatus(true);
  233. }, (err) => {
  234. console.error('加入房间失败: ', err);
  235. });
  236. },
  237. handlePublish: function () {
  238. this.client.publish(err => {
  239. console.error(`发布失败:错误码 - ${err.name},错误信息 - ${err.message}`);
  240. });
  241. },
  242. handlePublishScreen: function () {
  243. this.client.publish({ audio: false, video: false, screen: true }, err => {
  244. console.error(`发布失败:错误码 - ${err.name},错误信息 - ${err.message}`);
  245. });
  246. },
  247. handleUnpublish: function () {
  248. const {
  249. selectedStream
  250. } = this.state;
  251. if (!selectedStream) {
  252. alert('未选择需要取消发布的本地流');
  253. return;
  254. }
  255. this.client.unpublish(selectedStream.sid, (stream) => {
  256. console.info('取消发布本地流成功:', stream);
  257. const {
  258. localStreams
  259. } = this.state;
  260. const idx = localStreams.findIndex(item => item.sid === stream.sid);
  261. if (idx >= 0) {
  262. const p = localStreams.splice(idx, 1)[0];
  263. this.state.selectedStream = null;
  264. this.renderSelectedStream();
  265. this.unrenderStream(p);
  266. }
  267. }, (err) => {
  268. console.error('取消发布本地流失败:', err);
  269. })
  270. },
  271. handleSubscribe: function () {
  272. const {
  273. selectedStream
  274. } = this.state;
  275. if (!selectedStream) {
  276. alert('未选择需要订阅的远端流');
  277. return;
  278. }
  279. this.client.subscribe(selectedStream.sid, (err) => {
  280. console.error('订阅失败:', err);
  281. });
  282. },
  283. handleUnsubscribe: function () {
  284. const {
  285. selectedStream
  286. } = this.state;
  287. if (!selectedStream) {
  288. alert('未选择需要取消订阅的远端流');
  289. return;
  290. }
  291. this.client.unsubscribe(selectedStream.sid, (stream) => {
  292. console.info('取消订阅成功:', stream);
  293. const {
  294. remoteStreams
  295. } = this.state;
  296. const idx = remoteStreams.findIndex(item => item.sid === stream.sid);
  297. if (idx >= 0) {
  298. remoteStreams.splice(idx, 1, stream);
  299. this.rerenderStream(stream);
  300. }
  301. }, (err) => {
  302. console.error('订阅失败:', err);
  303. });
  304. },
  305. handleLeaveRoom: function () {
  306. const {
  307. isJoinedRoom
  308. } = this.state;
  309. console.log("离开房间:isJoinedRoom",isJoinedRoom)
  310. if (!isJoinedRoom) {
  311. return;
  312. }
  313. this.client.leaveRoom(() => {
  314. console.info('离开房间成功');
  315. this.state.selectedStream = null;
  316. this.renderSelectedStream();
  317. const {
  318. localStreams,
  319. remoteStreams
  320. } = this.state;
  321. localStreams.forEach(item => {
  322. this.unrenderStream(item);
  323. });
  324. remoteStreams.forEach(item => {
  325. this.unrenderStream(item);
  326. });
  327. this.renderRoomStatus(false);
  328. }, (err) => {
  329. console.error('离开房间失败:', err);
  330. });
  331. },
  332. handleSelectStream: function (stream) {
  333. console.log('select stream: ', stream);
  334. this.state.selectedStream = stream;
  335. this.renderSelectedStream(stream);
  336. }
  337. }
  338. App.init();
  339. }