Видео Twilio Remote не отображается в Angular - PullRequest
0 голосов
/ 13 апреля 2020

Здесь #localVideo и #remoteVideo - это ViewChild для включения видео

HTML


<div id="video-container">

  <div id="local" #localVideo>
    <p>local video</p>
  </div>

  <div id="remote" #remoteVideo>
    <p>remote video</p>
  </div>
  <input type="text" [(ngModel)]="username" placeholder="username">

  <input type="text" [(ngModel)]="roomName" placeholder="room name">

  <input type="button" [disabled]="!username || !roomName ? true : false" value="connect" (click)="connect()">

  <input type="button" [disabled]="!twilioService.roomObj ? true : false" value="disconnect" (click)="disconnect()">

</div>

Здесь можно получить доступ к Twilio с помощью API VIDEOCALL_SESSION, после чего я подключился для локального видео с помощью accessToken и Identity (userName) с Room (roomName). Локальное видео подключено успешно.

Когда я пытался подключить удаленное видео. что remoteVideo не показывает localVideo и аналогично localVideo также не показывает RemoteVideo.

Component.ts

import { TwilioVideoService } from '../_services/twilio-video.service';
@Component({
  selector: 'app-chat',
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit, OnDestroy {
  message1: string;
  accessToken: string;
  roomName: string;
  username: string;
  @ViewChild('localVideo') localVideo: ElementRef;
  @ViewChild('remoteVideo') remoteVideo: ElementRef;
  video_token: any;
constructor(private twilioService: TwilioVideoService,
            private serviceProxy: ServiceProxy){
           this.twilioService.msgSubject.subscribe(r => {
           this.message1 = r;
           });
           }

 ngOnInit() {

            this.twilioService.localVideo = this.localVideo;
            this.twilioService.remoteVideo = this.remoteVideo;
         }


  log(message) {
    this.message = message;
  }

  disconnect() {
    if (this.twilioService.roomObj && this.twilioService.roomObj !== null) {
      this.twilioService.roomObj.disconnect();
      this.twilioService.roomObj = null;
    }
  }

  async connect() {
    let storage = JSON.parse(localStorage.getItem('video_token') || '{}');
    if (!this.roomName || !this.username) { this.message1 = "enter username and room name."; return; }
    if (storage['video_token'] && storage['created_at'] + 3600000 > date) {
      this.accessToken = storage['video_token'];
      this.twilioService.connectToRoom(this.accessToken, { name: this.roomName, audio: true, video: 
 {width: 240 } })
      return;
    }
    let video_start = {
      userName: this.username,
      roomName: this.roomName
    }
    this.video_token = await this.serviceProxy.SingleRequest(ServiceRegistry.VIDEOCALL_SESSION,video_start);
    this.video_token = this.video_token.result;
    localStorage.setItem('video_token', JSON.stringify({
      video_token: this.video_token,
      created_at: date
    }));
    if (this.video_token.result != null)
      this.twilioService.connectToRoom(this.accessToken, { name: this.roomName, audio: true, video: {width: 240 } })
  }
}

В twilio-video.service.ts используется метод connect для соединения localVideo и RemoteVideo.

twilio-video.service.ts



  constructor(private http: HttpClient) { }



  connectToRoom(accessToken: string, options): void {
    connect(accessToken, options).then(room => {
      console.log(room)
      this.roomObj = room;

      if (!this.previewing && options['video']) {
        this.startLocalVideo();
        this.previewing = true;
      }

      room.participants.forEach(participant => {
        this.msgSubject.next("Already in Room: '" + participant.identity + "'");
        // console.log("Already in Room: '" + participant.identity + "'");
        // this.attachParticipantTracks(participant);
      });

      room.on('participantDisconnected', (participant) => {
        this.msgSubject.next("Participant '" + participant.identity + "' left the room");
        // console.log("Participant '" + participant.identity + "' left the room");

        this.detachParticipantTracks(participant);
      });

      room.on('participantConnected', (participant) => {
        console.log('remote video...')
        participant.tracks.forEach(track => {
          this.remoteVideo.nativeElement.appendChild(track.attach());
        });

        // participant.on('trackAdded', track => {
        //   console.log('track added')
        //   this.remoteVideo.nativeElement.appendChild(track.attach());
        //   // document.getElementById('remote-media-div').appendChild(track.attach());
        // });
      });

      // When a Participant adds a Track, attach it to the DOM.
      room.on('trackAdded', (track, participant) => {
        console.log(participant.identity + " added track: " + track.kind);
        this.attachTracks([track]);
      });

      // When a Participant removes a Track, detach it from the DOM.
      room.on('trackRemoved', (track, participant) => {
        console.log(participant.identity + " removed track: " + track.kind);
        this.detachTracks([track]);
      });

      room.once('disconnected', room => {
        this.msgSubject.next('You left the Room:' + room.name);
        room.localParticipant.tracks.forEach(track => {
          var attachedElements = track.detach();
          attachedElements.forEach(element => element.remove());
        });
      });
    });
  }

  attachParticipantTracks(participant): void {
    var tracks = Array.from(participant.tracks.values());
    this.attachTracks([tracks]);
  }

  attachTracks(tracks) {
    tracks.forEach(track => {
      this.remoteVideo.nativeElement.appendChild(track.attach());
    });
  }

  startLocalVideo(): void {
    createLocalVideoTrack().then(track => {
      this.localVideo.nativeElement.appendChild(track.attach());
    });
  }

  localPreview(): void {
    createLocalVideoTrack().then(track => {
      this.localVideo.nativeElement.appendChild(track.attach());
    });
  }

  detachParticipantTracks(participant) {
    var tracks = Array.from(participant.tracks.values());
    this.detachTracks(tracks);
  }

  detachTracks(tracks): void {
    tracks.forEach(function (track) {
      track.detach().forEach(function (detachedElement) {
        detachedElement.remove();
      });
    });
  }


...