Совместное использование экрана WebRT C не работает в текущем аудиопотоке - PullRequest
0 голосов
/ 21 апреля 2020

В моем проекте у меня есть аудио и видео 1-1, функции группового вызова. С помощью звонка пользователь также может поделиться экраном. В видеозвонке я реализовал общий доступ к экрану, и он отлично работает, но в аудиовызове общий доступ к экрану не работает. Я не уверен, почему это происходит.

Поток общего экрана может генерироваться, но с другой стороны он дает мне эту ошибку. DOMException: не удалось выполнить 'addIceCandidate' для 'RTCPeerConnection': ошибка при обработке кандидата ICE Иногда она показывает эту ошибку, а иногда не отображает никаких ошибок, и поток также не добавляется на другой стороне. Я не понимаю, почему это происходит.

Ниже приведен мой код добавления нового кандидата. Здесь возникает ошибка.

this.chatService.onVideoCandidate().subscribe((data: any) => {
      console.log("in candidate socket event", data);
      this.peerConnections[data.socketId]
        .addIceCandidate(new RTCIceCandidate(data.message))
        .catch(e => {
          console.log("in error", e);
          console.error(e);
        });
    });

Ниже приведен мой текущий код для обработки звуковых событий.

/ * При новом подключении приходит * /

 this.chatService.onVideoReady().subscribe((data: any) => {
      const id = data.id;
      const type = data.data.type;
      console.log(" id in videoready", id);
      if (id) {
        if (!this.localStream) {
          console.log("in return video ready");
          return;
        }
        let peerConnection = null;
        peerConnection = new RTCPeerConnection(this.config);
        this.peerConnections[id] = peerConnection;
        if (this.localStream) {
          peerConnection.addStream(this.localStream);
        }
        peerConnection
          .createOffer()
          .then(sdp => {
            peerConnection.setLocalDescription(sdp);
          })
          .then(() => {
            console.log("peer id", id);
            if (this.isScreenShare === true) {
              const data = {
                type: "screen",
                userName:
                  this.userData.firstName + " " + this.userData.lastName,
                userProfilePicture: this.userData.profilePictureURL
              };
              this.chatService.VideoOffer(
                id,
                peerConnection["localDescription"],
                data
              );
            } else {
              const data = {
                type: "face",
                userName:
                  this.userData.firstName + " " + this.userData.lastName,
                userProfilePicture: this.userData.profilePictureURL
              };
              this.chatService.VideoOffer(
                id,
                peerConnection["localDescription"],
                data
              );
            }
          })
          .catch(err => {
            console.log("error in onVideoready", err);
          });
        peerConnection.onaddstream = event =>
          this.handleRemoteStreamAdded(event.stream, id, data.data);
        peerConnection.onicecandidate = event => {
          if (event.candidate) {
            this.chatService.VideoCandidate(id, event.candidate);
          }
        };
      }
    });

/ * На видео предложение * /

this.chatService.onVideoOffer().subscribe((data: any) => {
      console.log("in offer socket event", data);
      let peerConnection: any = null;
      peerConnection = new RTCPeerConnection(this.config);
      this.peerConnections[data.socketId] = peerConnection;
      peerConnection.addStream(this.localStream);
      peerConnection
        .setRemoteDescription(data.message)
        .then(() => peerConnection.createAnswer())
        .then(sdp => peerConnection.setLocalDescription(sdp))
        .then(() => {
          console.log(
            "login person id",
            this.utilService.getCurrentLoginUserProfileId()
          );
          let answerData = {};
          answerData = {
            roomId: this.roomId,
            answeringUser: this.utilService.getCurrentLoginUserProfileId()
          };
          this.chatService.VideoAnswer(
            data.socketId,
            peerConnection.localDescription,
            answerData
          );
        });
      peerConnection.onaddstream = event =>
        this.handleRemoteStreamAdded(event.stream, data.socketId, data.data);
      peerConnection.onicecandidate = event => {
        if (event.candidate) {
          this.chatService.VideoCandidate(data.socketId, event.candidate);
        }
      };
    });

/ * На видео ответ * /

  this.chatService.onVideoAnswer().subscribe((data: any) => {
      this.peerConnections[data.socketId].setRemoteDescription(data.message);
    });

/ * Функция для запуска общего экрана * /

  startScreenShare() {
    navigator.mediaDevices["getDisplayMedia"](this.screenContraints)
      .then(stream => {
        this.isScreenShare = true;
        console.log("in start screen share stream", stream);
        this.screenShareStream = stream;
        if (stream) {
          this.getUserMediaSuccess(stream);
          stream.oninactive = () => {
            this.isScreenShare = false;

            if (!this.hangedUpWhileSSActive) {
              // checks if the user wants to hang up or wants to continue with the video streaming
              console.log('screen share failed');
              navigator.mediaDevices
                .getUserMedia(this.constraints)
                .then(stream => {
                  this.getUserMediaSuccess(stream);
                })
                .catch(err => {
                  /* handle the error */
                  console.log("in media err");
                  this.getUserMediaError(err);
                });
            }
          };
        }
      })
      .catch(err => {
        this.getUserMediaError(err);
      });
  }

/ * Ограничения для аудиопотока и общего потока экрана * /

this.config = {
      iceServers: [
        {
          urls: ["stun:stun.l.google.com:19302"]
        }
      ]
    };

    this.constraints = {
      audio: { echoCancellation: true },
      video: false
    };

    this.screenContraints = {
      audio: false,
      video: true
    };

Пожалуйста, дайте мне знать, где я делаю неправильно. Я надеюсь, что это не невозможно сделать совместное использование экрана в аудиопотоке.

...