live.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. import { ref, reactive } from 'vue';
  2. import { Message, Loading } from 'element-ui';
  3. import { useLive, useCommonLive, rtc } from '../common/common';
  4. import { DealStudentConnection, GetStudentInfo_Connection, GetLiveRoomInfo, StartGroup } from '@/api/live';
  5. import { useRoute } from 'vue-router/composables';
  6. import i18n from '@/locales/i18n';
  7. import store from '@/store';
  8. const {
  9. publishStream,
  10. getHistory,
  11. getDevice,
  12. createLocalStream,
  13. sendPublishMessage,
  14. handsDown: commonHandsDown,
  15. updateMcResult,
  16. roomUpdate,
  17. drawChange
  18. } = useLive();
  19. const { studentExitLiveRoom } = useCommonLive();
  20. /**
  21. * 教师直播特有的 rtc 方法
  22. */
  23. export function useTeacherLiveRtc() {
  24. /**
  25. * 开启直播
  26. */
  27. function startLive() {
  28. rtc.value.startLive({
  29. success(data) {
  30. console.log(data);
  31. publishStream('main'); // 如果需要立即推流,执行 publish 方法
  32. Message({
  33. message: i18n.t('Key452'),
  34. type: 'success'
  35. });
  36. },
  37. fail(data) {
  38. Message({
  39. message: `${i18n.t('Key453')}:${data}`,
  40. type: 'warning'
  41. });
  42. }
  43. });
  44. }
  45. /**
  46. * 结束直播
  47. */
  48. function stopLive() {
  49. rtc.value.stopLive({
  50. success() {
  51. // Message({
  52. // type: 'success',
  53. // message: i18n.t('Key454')
  54. // });
  55. console.log('结束直播成功');
  56. },
  57. fail(data) {
  58. // Message({
  59. // type: 'error',
  60. // message: `${i18n.t('Key455')}:${JSON.stringify(data)}`
  61. // });
  62. console.log('结束直播失败', data);
  63. }
  64. });
  65. }
  66. /**
  67. * 推送桌面共享
  68. */
  69. function publishShareStream() {
  70. rtc.value.publishShareStream({
  71. success: (stream) => {
  72. console.log('推送桌面共享成功', stream);
  73. },
  74. fail: (str) => {
  75. console.log(str);
  76. }
  77. });
  78. }
  79. /**
  80. * 关闭桌面共享
  81. */
  82. function unPubShareStream() {
  83. rtc.value.unPubShareStream();
  84. }
  85. /**
  86. * 踢出房间
  87. * @param {String} userid
  88. */
  89. function kickOut(userid) {
  90. rtc.value.kickOut(userid, (err) => {
  91. if (err === undefined) {
  92. Message.success('踢出成功');
  93. } else {
  94. Message.error('踢出失败');
  95. }
  96. });
  97. }
  98. /**
  99. * 开启、结束、暂停、恢复录制
  100. * @param { String } status: 'start' 开启, 'end' 结束, 'pause' 暂停, 'resume' 恢复
  101. */
  102. function liveRecord(status) {
  103. rtc.value.liveRecord({
  104. status,
  105. success(data) {
  106. console.log('成功', data);
  107. },
  108. fail(str) {
  109. console.log(str);
  110. }
  111. });
  112. }
  113. // 连麦
  114. /**
  115. * 老师端发起邀请,邀请学生上麦。(举手模式)
  116. * @param {Object} object
  117. */
  118. function invite(object) {
  119. rtc.value.invite(object);
  120. }
  121. // 文档
  122. // 获取文档列表
  123. function getInstructionAllDocument(success, failed) {
  124. rtc.value.getInstructionAllDocument({
  125. getInstructionAllDocumentSuccess: success,
  126. getInstructionAllDocumentFailed: failed
  127. });
  128. }
  129. // 获取单个文档详情
  130. function getSingleDocument(docId, callback) {
  131. rtc.value.getSingleDocument({
  132. docId,
  133. getSingleDocumentCallback: callback
  134. });
  135. }
  136. function docChange(obj) {
  137. rtc.value.docChange(obj);
  138. }
  139. return {
  140. startLive,
  141. stopLive,
  142. publishShareStream,
  143. unPubShareStream,
  144. liveRecord,
  145. invite,
  146. getInstructionAllDocument,
  147. getSingleDocument,
  148. docChange,
  149. kickOut
  150. };
  151. }
  152. /**
  153. * 初始化监听事件
  154. */
  155. export function useInitListener({
  156. roomData,
  157. chatList,
  158. device: devices,
  159. getLiveRoomData_DRTD,
  160. connect,
  161. callLoading,
  162. connectUid,
  163. dealStudentConnection,
  164. roomInfo,
  165. roomContext,
  166. liveStat,
  167. speakData,
  168. connectStudent,
  169. handsDownUid,
  170. task_id,
  171. setDevice,
  172. hasAudio,
  173. hasVideo,
  174. remoteStreamType
  175. }) {
  176. rtc.value.on('login_success', (data) => {
  177. console.log('登录成功', data);
  178. roomData.value = data;
  179. // 初始化画板需要的数据
  180. const canvasInitData = {
  181. allowDraw: true, // 是否具有书写画笔权限(讲师权限) true / false
  182. id: 'draw-parent',
  183. pptDisplay: 1, // 文档展示方式。默认0,按窗口 1,按宽度
  184. liveId: data.live.status === 1 ? data.live.id : '' // 如果直播已经开始,需将直播 id 传入 sdk 中
  185. };
  186. // 初始化画板
  187. rtc.value.canvasInit(canvasInitData);
  188. });
  189. rtc.value.on('login_failed', (data) => {
  190. console.log('登录失败', data);
  191. Message({
  192. message: `${i18n.t('Key443')}:${JSON.stringify(data)}`,
  193. type: 'warning'
  194. });
  195. });
  196. // 教师 必须在加入房间成功的事件回调里创建本地流
  197. rtc.value.on('conference_join', () => {
  198. console.log('加入房间成功');
  199. getHistory({
  200. success(data) {
  201. const chatLog = data.datas.meta.chatLog.map(({ content, userName }) => {
  202. return { msg: content, username: userName };
  203. });
  204. chatList.value = chatLog;
  205. },
  206. fail(str) {
  207. console.log(str);
  208. }
  209. });
  210. getDevice({
  211. success(data) {
  212. console.log('获取音视频设备成功', data);
  213. const device = store.state.app.liveDevice;
  214. devices.value = data;
  215. if (data.video.length === 0 && data.audio.length === 0) {
  216. Message({
  217. type: 'warning',
  218. message: i18n.t('Key444')
  219. });
  220. }
  221. const isVideo = device.video.length > 0 && data.video.some((item) => item.deviceId === device.video);
  222. const isAudio = device.audio.length > 0 && data.audio.some((item) => item.deviceId === device.audio);
  223. if (!isVideo && !isAudio) {
  224. setDevice(false);
  225. } else {
  226. createLocalStream('main', hasAudio, hasVideo);
  227. }
  228. },
  229. fail(str) {
  230. console.log('直播关闭状态或查询直播失败: ', str);
  231. Message({
  232. type: 'error',
  233. message: `${i18n.t('Key445')}: ${str}`
  234. });
  235. }
  236. });
  237. });
  238. rtc.value.on('conference_join_failed', (err) => {
  239. // 加入房间失败 err为错误原因
  240. console.log('加入房间失败', err);
  241. Message({
  242. message: `${i18n.t('Key446')}:${err}`,
  243. type: 'warning'
  244. });
  245. });
  246. /**
  247. * 新增订阅流事件
  248. */
  249. rtc.value.on('allow_sub', (tryStream) => {
  250. if (tryStream.isMixed()) {
  251. console.log('是混合流,不订阅');
  252. } else {
  253. // 订阅远程流
  254. rtc.value.trySubscribeStream({
  255. tryStream,
  256. success(stream) {
  257. // 订阅流成功
  258. const streamType = stream.streamType();
  259. remoteStreamType.value = streamType;
  260. console.log('订阅流成功', streamType);
  261. stream.show('student', 'contain'); // 将流显示到指定 id 的盒子中
  262. if (streamType === 1 || streamType === 10) {
  263. connect.value = true;
  264. callLoading.value = false;
  265. }
  266. if (streamType === 10) {
  267. dealStudentConnection(connectUid.value, 2, roomInfo.value.video_mode);
  268. }
  269. },
  270. fail(err) {
  271. console.log('订阅流失败', err);
  272. }
  273. });
  274. }
  275. });
  276. // 直播未开始,不能推流
  277. rtc.value.on('not_live', () => {
  278. console.log('直播未开始,不能推流');
  279. Message({
  280. message: i18n.t('Key402'),
  281. type: 'warning'
  282. });
  283. });
  284. // 推流前查询直播状态失败,导致没有推流
  285. rtc.value.on('local_stream_publish_failed', () => {
  286. console.log('推流前查询直播状态失败,导致没有推流');
  287. Message({
  288. message: i18n.t('Key403'),
  289. type: 'warning'
  290. });
  291. });
  292. // 房间全量信息事件(人员进出时广播)
  293. rtc.value.on('room_context', (roomData) => {
  294. roomContext.value = JSON.parse(roomData);
  295. getLiveRoomData_DRTD();
  296. console.log('房间全量信息事件(人员进出时广播)', JSON.parse(roomData));
  297. });
  298. rtc.value.on('publish_stream', (str) => {
  299. console.log('直播已开启', str);
  300. liveStat.value = true;
  301. });
  302. rtc.value.on('end_stream', (str) => {
  303. console.log('直播已关闭', str);
  304. liveStat.value = false;
  305. });
  306. rtc.value.on('switch_user_settings', (settingData) => {
  307. // 单个用户配置监听
  308. console.log(settingData);
  309. });
  310. // 人员列表事件(人员麦序变化时广播)
  311. rtc.value.on('speak_context', (_speakData) => {
  312. speakData.value = JSON.parse(_speakData);
  313. console.log('人员列表事件(人员麦序变化时广播)', JSON.parse(_speakData));
  314. });
  315. rtc.value.on('switch_settings', (data) => {
  316. console.log('房间设置事件', data); // 房间设置事件
  317. });
  318. // 单条流状态通知事件
  319. rtc.value.on('streamStatus', (data) => {
  320. console.log(data);
  321. });
  322. // 推流异常断开事件
  323. rtc.value.on('publishStreamErr', (data) => {
  324. // 直播开启状态下,尝试重推这条流
  325. console.log(`推流意外终止:${data.streamName}`);
  326. publishStream('main');
  327. });
  328. // 视频无法自动播放
  329. rtc.value.on('playError', (data) => {
  330. console.log('视频无法自动播放', data);
  331. });
  332. // 监听通知移除流事件
  333. rtc.value.on('stream_removed', (stream) => {
  334. console.log('监听通知移除流事件', stream);
  335. if ('room_user_id' in connectStudent.value && stream.streamType() === 10 && connect.value) {
  336. handsDownUid();
  337. }
  338. connect.value = false;
  339. remoteStreamType.value = -1;
  340. });
  341. // 停止订阅流
  342. rtc.value.on('unSub', (unSubStream) => {
  343. console.log('停止订阅流', unSubStream);
  344. rtc.value.unSubscribeStream({
  345. unSubStream,
  346. success(stream) {
  347. console.log('取消订阅流成功', stream.id());
  348. },
  349. fail(str) {
  350. console.log(str);
  351. }
  352. });
  353. });
  354. // 用户退出房间通知其他人员事件
  355. rtc.value.on('exit_room_user', (data) => {
  356. console.log('用户退出房间通知其他人员事件', data);
  357. studentExitLiveRoom(task_id, data.id, false);
  358. });
  359. /**
  360. * 排麦监听事件
  361. */
  362. // 监听自己被邀请事件
  363. rtc.value.on('inviteUp', (uid) => {
  364. console.log('监听自己被邀请事件', uid);
  365. rtc.value.inviteAccept({
  366. success(str) {
  367. console.log('接受邀请成功', str);
  368. },
  369. fail(data) {
  370. console.log('接受邀请失败', data);
  371. }
  372. });
  373. });
  374. /**
  375. * 监听聊天事件
  376. */
  377. rtc.value.on('chat_message', (data) => {
  378. const dat = JSON.parse(data);
  379. console.log(dat);
  380. // 敏感词过滤:如果发送的聊天消息被系统判定包含敏感词,则只有发送者能收到本条消息,房间内其他人都不会收到这条聊天消息。
  381. // 如果返回消息中有 isFilterChat 字段(消息不包含敏感词返回数据中无isFilterChat字段),且isFilterChat的值为1,则说明该消息包含敏感字,除发送者外其他人不会收到这条消息。
  382. if (dat.isFilterChat && dat.isFilterChat === 1) {
  383. return;
  384. }
  385. chatList.value.push(dat);
  386. });
  387. rtc.value.on('allowChatChange', ({ settings }) => {
  388. Message({
  389. type: 'success',
  390. message: settings.allow_chat ? i18n.t('Key633') : i18n.t('Key632')
  391. });
  392. });
  393. // 画笔数据事件
  394. rtc.value.on('draw', (data) => {
  395. const drawData = JSON.parse(data);
  396. console.log('画笔数据事件', drawData);
  397. });
  398. // 接收自定义消息
  399. rtc.value.on('publish_message', (data) => {
  400. // 连接中途下麦
  401. if (data.type === 'handsDown-load-student' && data.uid === connectUid.value) {
  402. callLoading.value = false;
  403. Message({
  404. type: 'warning',
  405. message: i18n.t('Key449')
  406. });
  407. }
  408. // 无对应设备
  409. if (data.type === 'no-device') {
  410. callLoading.value = false;
  411. Message({
  412. type: 'warning',
  413. message: data.video_mode === 1 ? i18n.t('Key451') : i18n.t('Key450')
  414. });
  415. }
  416. });
  417. }
  418. /**
  419. * 教师连麦/下麦处理
  420. * @param {Object} param0
  421. */
  422. export function useConnect({ connect, callLoading, connectStudent, roomInfo, connectUid, getLiveRoomData_DRTD }) {
  423. const route = useRoute();
  424. const task_id = route.query.task_id;
  425. /**
  426. * 学员连线处理
  427. * @param {String} room_user_id
  428. * @param {Number} deal_mode
  429. * @param {String} connection_mode
  430. */
  431. function dealStudentConnection(room_user_id, deal_mode, connection_mode) {
  432. DealStudentConnection({
  433. task_id,
  434. room_user_id,
  435. deal_mode,
  436. connection_mode
  437. }).then(() => {
  438. getLiveRoomData_DRTD();
  439. });
  440. }
  441. /**
  442. * rtc 上麦方法
  443. * @param {String} uid
  444. * @param {Object} connectStudent
  445. * @param {Number} mode
  446. */
  447. function inviteStudent(uid, connectStudent, mode) {
  448. rtc.value.invite({
  449. uid,
  450. success: (str) => {
  451. console.log('邀请上麦成功', str);
  452. dealStudentConnection(uid, 1, mode);
  453. sendPublishMessage({
  454. type: 'inviteImage',
  455. connectStudent
  456. });
  457. },
  458. fail: (data) => {
  459. console.log('邀请上麦失败:', data);
  460. callLoading.value = false;
  461. Message.error(`${i18n.t('Key430')}:${data.errorMsg}`);
  462. }
  463. });
  464. }
  465. /**
  466. * 老师邀请学生上麦
  467. * @param {Object} student
  468. * @param {Number} mode
  469. * @param {Boolean} is_mobile
  470. * @param {Boolean} is_exit_page
  471. * @returns
  472. */
  473. function invite(student, mode) {
  474. let is_mobile = student.is_mobile === 'true';
  475. let is_exit_page = student.is_exit_page === 'true';
  476. if (is_mobile && is_exit_page) {
  477. Message.warning(i18n.t('Key427'));
  478. return;
  479. }
  480. if (connect.value || callLoading.value) {
  481. Message.warning(i18n.t('Key428'));
  482. return;
  483. }
  484. callLoading.value = true;
  485. connectStudent.value = student;
  486. GetLiveRoomInfo({ task_id })
  487. .then(({ video_mode }) => {
  488. const uid = student.room_user_id;
  489. roomInfo.value.video_mode = mode;
  490. if (video_mode === mode) {
  491. inviteStudent(uid, student, mode);
  492. } else {
  493. roomUpdate({
  494. video_mode: mode,
  495. roomUpdateSuccess: (data) => {
  496. console.log(data, '连麦音视频模式更新请求成功!');
  497. inviteStudent(uid, student, mode);
  498. },
  499. roomUpdateFailed: () => {
  500. callLoading.value = false;
  501. Message.error(i18n.t('Key429'));
  502. }
  503. });
  504. }
  505. })
  506. .catch(() => {
  507. callLoading.value = false;
  508. });
  509. }
  510. // 下麦
  511. function handsDown_Live(uid) {
  512. commonHandsDown({
  513. uid,
  514. success: () => {
  515. if (callLoading.value) {
  516. sendPublishMessage({
  517. type: 'handsDown-load',
  518. uid
  519. });
  520. }
  521. dealStudentConnection(uid, 0, connectStudent.value.connection_mode);
  522. callLoading.value = false;
  523. connect.value = false;
  524. updateMcResult('', 0);
  525. Message.success(i18n.t('Key431'));
  526. connectStudent.value = {};
  527. },
  528. fail: (data) => {
  529. callLoading.value = false;
  530. connect.value = false;
  531. console.log('下麦失败', data);
  532. Message.warning(`${i18n.t('Key432')}:${data.errorMsg}`);
  533. }
  534. });
  535. }
  536. /**
  537. * 下麦
  538. * @param {String} uid
  539. */
  540. function handsDown(uid) {
  541. const _connectUid = typeof uid === 'string' ? uid : connectUid.value;
  542. if (_connectUid.length === 0) {
  543. GetStudentInfo_Connection({ task_id }).then(({ room_user_id }) => handsDown_Live(room_user_id));
  544. } else {
  545. handsDown_Live(_connectUid);
  546. }
  547. }
  548. return {
  549. invite,
  550. handsDown
  551. };
  552. }
  553. /**
  554. * 分组讨论
  555. * @param {String} task_id
  556. * @param {Object} router
  557. */
  558. export function useGroup(task_id, router) {
  559. let groupForm = reactive({
  560. operation_mode: 'group_count', // 操作方式 group_count【分成几组】 person_count【每组多少人】
  561. person_count: 1,
  562. group_count: 1
  563. });
  564. function startGroup() {
  565. const loading = Loading.service({
  566. text: i18n.t('Key437')
  567. });
  568. // 开始分组讨论
  569. StartGroup({ task_id, ...groupForm })
  570. .then(() => {
  571. Message.success(i18n.t('Key438'));
  572. router.push({
  573. path: '/new_live/teacher/group',
  574. query: {
  575. task_id
  576. }
  577. });
  578. })
  579. .finally(() => {
  580. loading.close();
  581. });
  582. }
  583. return {
  584. groupForm,
  585. startGroup
  586. };
  587. }
  588. export function useWhiteboard() {
  589. let isDrawSetting = ref(false);
  590. let curColor = ref('#343434');
  591. let drawColorList = ['#FF4747', '#343434', '#628EFF', '#FFCA0E'];
  592. let drawThicknessList = ['1', '3', '5'];
  593. // 画笔变更
  594. function changeDraw(action, value) {
  595. if (action === 'color') {
  596. drawChange(action, parseInt(Number(value.replace('#', '0x'))));
  597. curColor.value = value;
  598. } else {
  599. drawChange(action, value);
  600. }
  601. isDrawSetting.value = false;
  602. }
  603. return {
  604. isDrawSetting,
  605. curColor,
  606. drawColorList,
  607. drawThicknessList,
  608. changeDraw
  609. };
  610. }