浏览代码

直播接入声网

warrior 4 月之前
父节点
当前提交
e584d06850

+ 2 - 2
projects/live-app/src/app/components/live/live.component.html

@@ -1,7 +1,7 @@
 <div class="video_box" id="video-box">
-  <!-- <div class="camera_box"> -->
+  <div class="camera_box">
     <canvas id="canvas" width="100%" height="100%" style="display:none"></canvas>
     <div class="video" id="video" width="100%" height="100%">
     </div>
-  <!-- </div> -->
+  </div>
 </div>

+ 3 - 2
projects/live-app/src/app/components/live/live.component.scss

@@ -1,16 +1,17 @@
 .video_box {
-  background-color: #ffca22;
+  background-color: #000;
   width: 100%;
   height: 100vh;
   // border-radius: 2px;
   // border: 0.5px solid #a1a1a1;
+  position: absolute;
   .camera_box {
     // margin-top: 10px;
     position: relative;
     .video {
       // border-radius: 8px;
       width: 100%;
-      height: 100%;
+      height: 100vh;
     }
   }
 }

+ 119 - 86
projects/live-app/src/app/components/live/live.component.ts

@@ -19,31 +19,37 @@ declare const AgoraRTC: any;
   imports: [IonicModule, FormsModule],
 })
 export class LiveComponent implements OnInit {
-  profile?:Parse.Object
+  profile?: Parse.Object;
   rid?: string;
   room?: Parse.Object;
-  client: any //客户端
-  options:{appid:string,channel:string,uid:string|null,token:string} = {
-    appid: 'f4f19322cdb1412ab44343613bb7535f',
+  client: any; //客户端
+  options: {
+    appid: string;
+    channel: string;
+    uid: string | undefined;
+    token: string;
+  } = {
+    appid: '',
     channel: '',
-    uid: null,
-    token: ''
+    uid: '',
+    token: '',
   };
   localTracks: any = {
     audioTrack: null,
-    videoTrack: null
+    videoTrack: null,
   };
   constructor(
     public toastController: ToastController,
     private loadingCtrl: LoadingController,
     private activateRoute: ActivatedRoute,
-    private aiSer:AiChatService,
-    private http:HttpService
-  ) { }
+    private aiSer: AiChatService,
+    private http: HttpService
+  ) {}
 
   ngOnInit() {
-    this.client = AgoraRTC.createClient({ mode: "live", codec: "h264" });
-    AgoraRTC.enableLogUpload()
+    this.client = AgoraRTC.createClient({ mode: 'live', codec: 'h264' });
+    AgoraRTC.enableLogUpload();
+    this.getDevices();
     this.activateRoute.paramMap.subscribe(async (params) => {
       let rid: any = params.get('rid');
       this.rid = rid;
@@ -53,6 +59,33 @@ export class LiveComponent implements OnInit {
       this.getRoom();
     });
   }
+  // 获取所有音视频设备
+  getDevices() {
+    AgoraRTC.getDevices()
+      .then((devices: any) => {
+        const audioDevices = devices.filter(function (device: any) {
+          return device.kind === 'audioinput';
+        });
+        const videoDevices = devices.filter(function (device: any) {
+          return device.kind === 'videoinput';
+        });
+
+        var selectedMicrophoneId = audioDevices[0].deviceId;
+        var selectedCameraId = videoDevices[0].deviceId;
+        return Promise.all([
+          AgoraRTC.createCameraVideoTrack({ cameraId: selectedCameraId }),
+          AgoraRTC.createMicrophoneAudioTrack({
+            microphoneId: selectedMicrophoneId,
+          }),
+        ]);
+      })
+      .then((tracks: any) => {
+        console.log('createCameraVideoTrack', tracks);
+      })
+      .catch((err: any) => {
+        console.log(err);
+      });
+  }
   async getRoom() {
     let query = new Parse.Query('Room');
     query.equalTo('objectId', this.rid);
@@ -60,86 +93,86 @@ export class LiveComponent implements OnInit {
     query.include('user');
     this.room = await query.first();
     let queryProfile = new Parse.Query('Profile');
-    query.equalTo('user', this.room?.get('user').id);
+    queryProfile.equalTo('user', this.room?.get('user').id);
     queryProfile.notEqualTo('isDeleted', true);
     this.profile = await queryProfile.first();
+    this.getToken()
   }
   async getToken() {
-    let baseurl = 'https://server.masterol.cn/api/webrtc/build_token'
+    let baseurl = 'https://server.fmode.cn/api/webrtc/build_token';
     let reqBody = {
-      company: this.aiSer.company,
-      profile: localStorage.getItem('profileId'),
-      channelName: localStorage.getItem('profileId'),
-      department: localStorage.getItem('department'),
-      exam: localStorage.getItem('exam')
-    }
-
-    let data:any = this.http.httpRequst(baseurl,reqBody)
-    console.log(data)
+      company:'9aMy8gAuey',// this.aiSer.company,
+      profile: this.profile?.id,
+      channelName: this.profile?.id,
+      // department: localStorage.getItem('department'),
+      // exam: localStorage.getItem('exam'),
+    };
+    let data: any = await this.http.httpRequst(baseurl, reqBody,'POST');
+    console.log(data);
     if (data.code == 200) {
-      this.options.token = data.data.token,
-        this.options.appid = data.data.appid,
-        this.options.channel = localStorage.getItem('profileId')??'',
-      this.options.uid = localStorage.getItem('profileId')
-      await this.join()
+      (this.options.token = data.data.token),
+        (this.options.appid = data.data.appid),
+        (this.options.channel = this.profile?.id ?? ''),
+        (this.options.uid = this.profile?.id);
+      // await this.join();
     }
   }
-    // 进入频道
-    async join() {
-      let data = await Promise.all([
-        // join the channel
-        this.client.join(this.options.appid, this.options.channel, this.options.token, 111111),
-  
-        // create local tracks, using microphone and camera
-        AgoraRTC.createMicrophoneAudioTrack(),
-        AgoraRTC.createCameraVideoTrack()
-      ]);
-      await this.client.setClientRole('host')
-      console.log(data);
-      this.localTracks.audioTrack = data[1]
-      this.localTracks.videoTrack = data[2]
-  
-      this.localTracks.videoTrack.play("video");
-  
-      let publish = await this.client.publish(Object.values(this.localTracks));
-  
-      // getCurrentFrameData 获取当前渲染的视频帧数据。
-      // 订阅监考端音视频
-      this.client.on('user-published', async (user:any, mediaType:any) => {
-        console.log('user-published')
-        await this.client.subscribe(user, mediaType)
-        if (mediaType == "audio" && user.uid != 333333) {
-          console.log(mediaType, user)
-          //远端老师发出语音对话提示
-          // this.createBasicNotification('请注意,监考老师已向你发出语音通话!', 'info', '语音通话提示')
-          const remoteAudioTrack = user.audioTrack
-          remoteAudioTrack.setVolume(100)
-          remoteAudioTrack.play()
-        }
-      })
-      // 查询远端用户是否存在小程序端用户
-      this.joinReady()
-    }
-    async joinReady() {
-      console.log(this.client.remoteUsers)
-      let wxRemoteUsers = this.client.remoteUsers.find((item:any) => {
-        if (item.uid && item._video_added_) {
-          return item
-        }
-      })
-      console.log(wxRemoteUsers)
-      this.client.on("user-published", async (user:any, mediaType:any) => {
-        if(user.uid == 333333) {
-          await this.client.subscribe(user, mediaType);
-          console.log('用户推流成功')
-      
-        }
-      })
-      this.client.on("user-unpublished", (user:any) => {
-        if(user.uid == 333333) {
-          console.log('用户取消推流')
-    
-        }
-      })
-    }
+  // 进入频道
+  async join() {
+    let data = await Promise.all([
+      // join the channel
+      this.client.join(
+        this.options.appid,
+        this.options.channel,
+        this.options.token,
+        111111
+      ),
+
+      // create local tracks, using microphone and camera
+      AgoraRTC.createMicrophoneAudioTrack(),
+      AgoraRTC.createCameraVideoTrack(),
+    ]);
+    await this.client.setClientRole('host');
+    this.localTracks.audioTrack = data[1];
+    this.localTracks.videoTrack = data[2];
+    this.localTracks.videoTrack.play('video');
+    let publish = await this.client.publish(Object.values(this.localTracks));
+
+    // getCurrentFrameData 获取当前渲染的视频帧数据。
+    // 订阅监考端音视频
+    this.client.on('user-published', async (user: any, mediaType: any) => {
+      console.log('user-published');
+      await this.client.subscribe(user, mediaType);
+      if (mediaType == 'audio' && user.uid != 333333) {
+        console.log(mediaType, user);
+        //远端老师发出语音对话提示
+        // this.createBasicNotification('请注意,监考老师已向你发出语音通话!', 'info', '语音通话提示')
+        const remoteAudioTrack = user.audioTrack;
+        remoteAudioTrack.setVolume(100);
+        remoteAudioTrack.play();
+      }
+    });
+    // 查询远端用户是否存在小程序端用户
+    this.joinReady();
+  }
+  async joinReady() {
+    console.log(this.client.remoteUsers);
+    let wxRemoteUsers = this.client.remoteUsers.find((item: any) => {
+      if (item.uid && item._video_added_) {
+        return item;
+      }
+    });
+    console.log(wxRemoteUsers);
+    this.client.on('user-published', async (user: any, mediaType: any) => {
+      if (user.uid == 333333) {
+        await this.client.subscribe(user, mediaType);
+        console.log('用户推流成功');
+      }
+    });
+    this.client.on('user-unpublished', (user: any) => {
+      if (user.uid == 333333) {
+        console.log('用户取消推流');
+      }
+    });
+  }
 }

+ 3 - 0
projects/live-app/src/moduls/live/link-page/link-page.component.scss

@@ -10,6 +10,7 @@
     width: 100%;
     padding: 10px;
     color: white;
+    z-index: 1;
     .room-data{
       background-color: rgb(0 0 0 / 40%);
       display: flex;
@@ -18,6 +19,7 @@
       align-items: center;
       border-radius: 40px;
       padding: 4px;
+      border: 1px solid rgb(255 255 255 / 30%);
       .avatar{
         width: 36px;
         height: 36px;
@@ -54,6 +56,7 @@
       display: flex;
       align-items: center;
       justify-content: center;
+      border: 1px solid rgb(255 255 255 / 30%);
       ion-icon{
         font-size: 26px;
       }

+ 40 - 33
projects/live-app/src/services/http.service.ts

@@ -1,58 +1,65 @@
 import { Injectable } from '@angular/core';
-import { HttpClient,HttpHeaders } from '@angular/common/http';
+import { HttpClient, HttpHeaders } from '@angular/common/http';
 
 @Injectable({
-  providedIn: 'root'
+  providedIn: 'root',
 })
 export class HttpService {
+  constructor(public http: HttpClient) {}
 
-  constructor(public http: HttpClient) { }
-
-  customSQL(sql:string){
-    return new Promise((resolve,reason)=>{
-      this.http.post('https://server.fmode.cn/api/novaql/select',{
-        sql
-      }).subscribe(data=> {
-        resolve (data)
-      })
-    })
+  customSQL(sql: string) {
+    return new Promise((resolve, reason) => {
+      this.http
+        .post('https://server.fmode.cn/api/novaql/select', {
+          sql,
+        })
+        .subscribe((data) => {
+          resolve(data);
+        });
+    });
   }
 
   // 定义get请求方法
   getMsg(url: string, params: any) {
     return this.http.get(url, {
-      params
+      params,
     });
   }
 
-  postAuth(company:string,idCard:string,name:string){
-    return new Promise((resolve,reason)=>{
-      this.http.post('https://server.fmode.cn/api/apig/idcard',{
-        company:company,
-        cardNo:idCard,
-        realName:name
-      }).subscribe(data=> {
-        resolve (data)
-      })
-    })
+  postAuth(company: string, idCard: string, name: string) {
+    return new Promise((resolve, reason) => {
+      this.http
+        .post('https://server.fmode.cn/api/apig/idcard', {
+          company: company,
+          cardNo: idCard,
+          realName: name,
+        })
+        .subscribe((data) => {
+          resolve(data);
+        });
+    });
   }
 
-
   // 定义jsonp的方法
   getJsonpMsg(url: string, cb: string) {
     return this.http.jsonp(url, cb);
   }
 
-  async httpRequst(url:string,reqBody:any,method?:string){
-    let result = await fetch(url,{
-      method:method || 'GET',
+  async httpRequst(url: string, reqBody: any, method: string = 'GET') {
+    let queryString = '';
+    if (method === 'GET' && reqBody) {
+      queryString = new URLSearchParams(reqBody).toString();
+      url += `?${queryString}`;
+    }
+    let result = await fetch(url, {
+      method: method,
       headers: {
-        "Content-Type": "application/json",
+        'Content-Type': 'application/json',
       },
-      body:JSON.stringify(reqBody) 
-    })
-    let data = await result.json()
-    return data
+      body: method !== 'GET' ? JSON.stringify(reqBody) : undefined,
+    });
+    let data = await result.json();
+    console.log(data);
+    return data;
   }
-
 }