live.service.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import { Injectable } from '@angular/core';
  2. import * as Parse from 'parse';
  3. import { AiChatService } from './aichart.service';
  4. import { HttpService } from './http.service';
  5. declare const AgoraRTC: any;
  6. @Injectable({
  7. providedIn: 'root',
  8. })
  9. export class LiveService {
  10. options: {
  11. appid: string;
  12. channel: string;
  13. token: string;
  14. } = {
  15. appid: '71d3357d920d4352b39ec8b8d26a7cb9',
  16. channel: '',
  17. token: '',
  18. };
  19. localTracks: any = {
  20. audioTrack: null,
  21. videoTrack: null,
  22. };
  23. rid?: string; //房间id(channel)
  24. profile?:any = localStorage.getItem('profile');
  25. client: any; //客户端
  26. company: string = '';
  27. UID:any
  28. constructor(private http: HttpService, private aiServ: AiChatService) {
  29. this.client?.leave();
  30. this.company = this.aiServ.company;
  31. this.getProfile();
  32. }
  33. async getProfile() {
  34. if(this.profile) return
  35. let queryProfile = new Parse.Query('Profile');
  36. queryProfile.equalTo('user', Parse.User.current()?.id);
  37. queryProfile.notEqualTo('isDeleted', true);
  38. queryProfile.equalTo('isCross', true);
  39. let r = await queryProfile.first();
  40. this.profile = r?.id
  41. }
  42. /* 初始化Agora */
  43. initAgora() {
  44. this.client = AgoraRTC.createClient({ mode: 'rtc', codec: 'h264' });
  45. AgoraRTC.enableLogUpload();
  46. }
  47. // 获取所有音视频设备
  48. getDevices() {
  49. AgoraRTC.getDevices()
  50. .then((devices: any) => {
  51. const audioDevices = devices.filter(function (device: any) {
  52. return device.kind === 'audioinput';
  53. });
  54. const videoDevices = devices.filter(function (device: any) {
  55. return device.kind === 'videoinput';
  56. });
  57. let selectedMicrophoneId = audioDevices[0].deviceId;
  58. let selectedCameraId = videoDevices[0].deviceId;
  59. return Promise.all([
  60. AgoraRTC.createCameraVideoTrack({ cameraId: selectedCameraId }),
  61. AgoraRTC.createMicrophoneAudioTrack({
  62. microphoneId: selectedMicrophoneId,
  63. }),
  64. ]);
  65. })
  66. .then((tracks: any) => {
  67. console.log('createCameraVideoTrack', tracks);
  68. })
  69. .catch((err: any) => {
  70. console.log(err);
  71. });
  72. }
  73. async getToken(room: Parse.Object) {
  74. //获取频道token记录
  75. if (room?.get('profile').id == this.profile) {
  76. this.UID = 111111
  77. let uid = Parse.User.current()?.id;
  78. if (!uid) {
  79. return;
  80. }
  81. let baseurl = 'https://server.fmode.cn/api/webrtc/build_token';
  82. let reqBody = {
  83. company: this.company, // this.aiSer.company,
  84. profile: this.profile,
  85. channelName: this.profile,
  86. };
  87. let data: any = await this.http.httpRequst(baseurl, reqBody, 'POST');
  88. console.log(data);
  89. if (data.code == 200) {
  90. this.options.token = data.data.token;
  91. this.options.appid = data.data.appid;
  92. this.options.channel = room?.get('profile').id
  93. }
  94. } else {
  95. let data = await this.updateToken(room?.get('profile').id);
  96. this.options.token = data.token;
  97. this.options.channel = data.channel;
  98. console.log(data);
  99. }
  100. }
  101. /* 获取token */
  102. async updateToken(pid: string) {
  103. let sql = `select "rtc"."objectId" as "rid","rtc"."channel", "rtc"."token", "rtc"."expiraTime" from "RtcToken" as "rtc" where "rtc"."profile" = '${pid}' and "rtc"."expiraTime" >= now() order by "createdAt" desc limit 1`;
  104. let tokenData: any = await this.http.customSQL(sql);
  105. if (
  106. tokenData &&
  107. tokenData.code == 200 &&
  108. tokenData.data &&
  109. tokenData.data.length > 0
  110. ) {
  111. return tokenData.data[0];
  112. } else {
  113. return null;
  114. }
  115. }
  116. // 进入频道
  117. async join() {
  118. let data = await Promise.all([
  119. this.client.join(this.options.appid, this.options.channel, this.options.token, this.UID),
  120. /* 创建音频和视频轨道 */
  121. AgoraRTC.createMicrophoneAudioTrack(),
  122. AgoraRTC.createCameraVideoTrack(),
  123. ]);
  124. // await this.client.setClientRole('host');
  125. this.localTracks.audioTrack = data[1];
  126. this.localTracks.videoTrack = data[2];
  127. let remoteEle = document.getElementById('vice-video');
  128. if (remoteEle) {
  129. remoteEle.textContent = '';
  130. }
  131. this.localTracks.videoTrack.play('vice-video'); //播放自己视频渲染
  132. let publish = await this.client.publish(Object.values(this.localTracks));
  133. this.joinReady();
  134. }
  135. /* 订阅远程视频 */
  136. async joinReady() {
  137. console.log(this.client.remoteUsers);
  138. let wxRemoteUsers = this.client.remoteUsers.find((item: any) => {
  139. if (item.uid && item._video_added_) {
  140. return item;
  141. }
  142. });
  143. console.log(wxRemoteUsers);
  144. this.client.on('user-joined', (user: any) => {
  145. console.log(user, `${user.uid} 加入频道`);
  146. });
  147. this.client.on('user-published', async (user: any, mediaType: any) => {
  148. console.log('用户推流成功');
  149. // if (user.uid == 333333) {
  150. await this.client.subscribe(user, mediaType);
  151. // }
  152. let remoteEle = document.getElementById('video');
  153. if (remoteEle) {
  154. remoteEle.textContent = '';
  155. }
  156. if (mediaType === 'video') {
  157. user.videoTrack.play(`video`);
  158. }
  159. if (mediaType === 'audio') {
  160. user.audioTrack.play();
  161. }
  162. });
  163. this.client.on('user-unpublished', (user: any) => {
  164. let remoteEle = document.getElementById('video');
  165. if (remoteEle) {
  166. remoteEle.textContent = '对方离开直播间';
  167. }
  168. // if (user.uid == 333333) {
  169. console.log('用户取消推流');
  170. // }
  171. });
  172. }
  173. }