index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. window.onload = function () {
  2. const {
  3. AppId,
  4. AppKey
  5. } = window.config || {};
  6. // 此处使用固定的房间号的随机的用户ID,请自行替换
  7. const RoomId = "ssss02";
  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. const oldStream = streams.splice(idx, 1, current)[0];
  199. this.unrenderStream(oldStream);
  200. streams.push(current);
  201. this.renderStream(current);
  202. }
  203. });
  204. document.querySelector('#joinRoomBtn').addEventListener('click', this.handleJoinRoom.bind(this));
  205. document.querySelector('#publishBtn').addEventListener('click', this.handlePublish.bind(this));
  206. document.querySelector('#publishScreenBtn').addEventListener('click', this.handlePublishScreen.bind(this));
  207. document.querySelector('#unPublishBtn').addEventListener('click', this.handleUnpublish.bind(this));
  208. document.querySelector('#subscribeBtn').addEventListener('click', this.handleSubscribe.bind(this));
  209. document.querySelector('#unSubscribeBtn').addEventListener('click', this.handleUnsubscribe.bind(this));
  210. document.querySelector('#leaveRoomBtn').addEventListener('click', this.handleLeaveRoom.bind(this));
  211. window.addEventListener('beforeunload', this.handleLeaveRoom.bind(this));
  212. },
  213. // 操作
  214. handleJoinRoom: function () {
  215. const {
  216. roomId,
  217. userId,
  218. isJoinedRoom
  219. } = this.state;
  220. if (isJoinedRoom) {
  221. alert('已经加入了房间');
  222. return;
  223. }
  224. if (!roomId) {
  225. alert('请先填写房间号');
  226. return;
  227. }
  228. this.client.joinRoom(roomId, userId, () => {
  229. console.info('加入房间成功');
  230. this.renderRoomStatus(true);
  231. }, (err) => {
  232. console.error('加入房间失败: ', err);
  233. });
  234. },
  235. handlePublish: function () {
  236. this.client.publish(err => {
  237. console.error(`发布失败:错误码 - ${err.name},错误信息 - ${err.message}`);
  238. });
  239. },
  240. handlePublishScreen: function () {
  241. this.client.publish({ audio: false, video: false, screen: true }, err => {
  242. console.error(`发布失败:错误码 - ${err.name},错误信息 - ${err.message}`);
  243. });
  244. },
  245. handleUnpublish: function () {
  246. const {
  247. selectedStream
  248. } = this.state;
  249. if (!selectedStream) {
  250. alert('未选择需要取消发布的本地流');
  251. return;
  252. }
  253. this.client.unpublish(selectedStream.sid, (stream) => {
  254. console.info('取消发布本地流成功:', stream);
  255. const {
  256. localStreams
  257. } = this.state;
  258. const idx = localStreams.findIndex(item => item.sid === stream.sid);
  259. if (idx >= 0) {
  260. const p = localStreams.splice(idx, 1)[0];
  261. this.state.selectedStream = null;
  262. this.renderSelectedStream();
  263. this.unrenderStream(p);
  264. }
  265. }, (err) => {
  266. console.error('取消发布本地流失败:', err);
  267. })
  268. },
  269. handleSubscribe: function () {
  270. const {
  271. selectedStream
  272. } = this.state;
  273. if (!selectedStream) {
  274. alert('未选择需要订阅的远端流');
  275. return;
  276. }
  277. this.client.subscribe(selectedStream.sid, (err) => {
  278. console.error('订阅失败:', err);
  279. });
  280. },
  281. handleUnsubscribe: function () {
  282. const {
  283. selectedStream
  284. } = this.state;
  285. if (!selectedStream) {
  286. alert('未选择需要取消订阅的远端流');
  287. return;
  288. }
  289. this.client.unsubscribe(selectedStream.sid, (stream) => {
  290. console.info('取消订阅成功:', stream);
  291. const {
  292. remoteStreams
  293. } = this.state;
  294. const idx = remoteStreams.findIndex(item => item.sid === stream.sid);
  295. if (idx >= 0) {
  296. remoteStreams.splice(idx, 1, stream);
  297. this.rerenderStream(stream);
  298. }
  299. }, (err) => {
  300. console.error('订阅失败:', err);
  301. });
  302. },
  303. handleLeaveRoom: function () {
  304. const {
  305. isJoinedRoom
  306. } = this.state;
  307. if (!isJoinedRoom) {
  308. return;
  309. }
  310. this.client.leaveRoom(() => {
  311. console.info('离开房间成功');
  312. this.state.selectedStream = null;
  313. this.renderSelectedStream();
  314. const {
  315. localStreams,
  316. remoteStreams
  317. } = this.state;
  318. localStreams.forEach(item => {
  319. this.unrenderStream(item);
  320. });
  321. remoteStreams.forEach(item => {
  322. this.unrenderStream(item);
  323. });
  324. this.renderRoomStatus(false);
  325. }, (err) => {
  326. console.error('离开房间失败:', err);
  327. });
  328. },
  329. handleSelectStream: function (stream) {
  330. console.log('select stream: ', stream);
  331. this.state.selectedStream = stream;
  332. this.renderSelectedStream(stream);
  333. }
  334. }
  335. App.init();
  336. }