@Galdar
Web, JS, PHP, NGINX, Linux

Почему не отображается видео стрим?

Добрый день, дорогие знатоки. Ломаю голову не могу догнать в чем тут проблема. Пытаюсь по примерам сделать видео чат и он вроде как да же получился, но видео и звук другого пользователя появляется только после перезагрузки страницы. Как исправить и сделать так чтобы видео стрим другого пользователя появлялся сразу после подключения?

html-js

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>videoChatApp</title>

    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
    <script src="https://kit.fontawesome.com/c939d0e917.js"></script>
    <script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"></script>
    <script>
      const ROOM_ID = "<%= roomId %>";
    </script>

  </head>
  <body>
    <div class="header">
      <div class="logo">
        <div class="header__back">
          <i class="fas fa-angle-left"></i>
        </div>
        <h3>Video Chat</h2>
      </div>
    </div>  
    <div class="main">  
    <div class="main__left">
      <div class="videos__group">
        <div id="video-grid">

        </div>
      </div>
      <div class="options">
        <div class="options__left">
          <div id="stopVideo" class="options__button">
            <i class="fa fa-video-camera"></i>
          </div>
          <div id="muteButton" class="options__button">
            <i class="fa fa-microphone"></i>
          </div>
          <div id="showChat" class="options__button">
            <i class="fa fa-comment"></i>
          </div>
        </div>
        <div class="options__right">
          <div id="inviteButton" class="options__button">
            <i class="fas fa-user-plus"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="main__right">
      <div class="main__chat_window">
          <div class="messages">

          </div>
      </div>
      <div class="main__message_container">
        <input id="chat_message" type="text" autocomplete="off" placeholder="Type message here...">
        <div id="send" class="options__button">
          <i class="fa fa-plus" aria-hidden="true"></i>
        </div>
      </div>
    </div>
  </div>
  </body>
  <script type="text/javascript">

    const socket = io.connect("/", {
      forceNew: true,
      transports: ["polling"]
    });

    const videoGrid = document.getElementById("video-grid");
    const myVideo = document.createElement("video");
    const showChat = document.querySelector("#showChat");
    const backBtn = document.querySelector(".header__back");
    myVideo.muted = true;

    console.log(myVideo)

    backBtn.addEventListener("click", () => {
      document.querySelector(".main__left").style.display = "flex";
      document.querySelector(".main__left").style.flex = "1";
      document.querySelector(".main__right").style.display = "none";
      document.querySelector(".header__back").style.display = "none";
    });

    showChat.addEventListener("click", () => {
      document.querySelector(".main__right").style.display = "flex";
      document.querySelector(".main__right").style.flex = "1";
      document.querySelector(".main__left").style.display = "none";
      document.querySelector(".header__back").style.display = "block";
    });

    const user = prompt("Enter your name");

    const peer = new Peer(undefined, {
      path: "/peerjs",
      host: "/",
      port: "443",
    });

    // Добавление стрима на страницу
    const addVideoStream = (video, stream) => {
      
      console.log( 'addVideoStream' )
      console.log(video)

      video.srcObject = stream;
      video.addEventListener("loadedmetadata", () => {

        video.play();

        videoGrid.append(video);

      });

    };

    // Подключение нового пользователя
    const connectToNewUser = (userId, stream) => {

      console.log("connectToNewUser")
      console.log("userId", userId)
      console.log("stream", stream)

      const call = peer.call(userId, stream);

      console.log("call", call)

      const video = document.createElement("video");

      console.log("video", video)

      call.on("stream", ( userVideoStream ) => {

        console.log("stream")
        console.log(userVideoStream)
        addVideoStream(video, userVideoStream);

      });

    };

    let myVideoStream;
    navigator.mediaDevices
    .getUserMedia({
      audio: true,
      video: true,
    })
    .then( (stream) => {

      myVideoStream = stream;

      addVideoStream(myVideo, stream);

      peer.on("call", (call) => {

        console.log("call")

        call.answer(stream);

        const video = document.createElement("video");

        call.on("stream", (userVideoStream) => {

          console.log( userVideoStream )

          addVideoStream(video, userVideoStream);

        });

      });

      // Получение сообщение о новом подключении пользователя
      socket.on("user-connected", (userId) => {

        console.log("user-connected");

        console.log( userId );

        connectToNewUser(userId, stream);

      });

    });

    peer.on("open", (id) => {

      console.log("open");
      
      socket.emit("join-room", ROOM_ID, id, user);

    });



    let text = document.querySelector("#chat_message");
    let send = document.getElementById("send");
    let messages = document.querySelector(".messages");

    send.addEventListener("click", (e) => {

      if (text.value.length !== 0) {
        socket.emit("message", text.value);
        text.value = "";
      }

    });

    text.addEventListener("keydown", (e) => {

      if (e.key === "Enter" && text.value.length !== 0) {
        socket.emit("message", text.value);
        text.value = "";
      }

    });

    const inviteButton = document.querySelector("#inviteButton");
    const muteButton = document.querySelector("#muteButton");
    const stopVideo = document.querySelector("#stopVideo");

    muteButton.addEventListener("click", () => {

      const enabled = myVideoStream.getAudioTracks()[0].enabled;

      console.log( enabled )

      if (enabled) 
      {
        myVideoStream.getAudioTracks()[0].enabled = false;
        html = `<i class="fas fa-microphone-slash"></i>`;
        muteButton.classList.toggle("background__red");
        muteButton.innerHTML = html;
      } 
      else 
      {
        myVideoStream.getAudioTracks()[0].enabled = true;
        html = `<i class="fas fa-microphone"></i>`;
        muteButton.classList.toggle("background__red");
        muteButton.innerHTML = html;
      }

    });

    stopVideo.addEventListener("click", () => {
      const enabled = myVideoStream.getVideoTracks()[0].enabled;
      if (enabled) 
      {
        myVideoStream.getVideoTracks()[0].enabled = false;
        html = `<i class="fas fa-video-slash"></i>`;
        stopVideo.classList.toggle("background__red");
        stopVideo.innerHTML = html;
      } 
      else 
      {
        myVideoStream.getVideoTracks()[0].enabled = true;
        html = `<i class="fas fa-video"></i>`;
        stopVideo.classList.toggle("background__red");
        stopVideo.innerHTML = html;
      }
    });

    inviteButton.addEventListener("click", (e) => {
      prompt(
        "Copy this link and send it to people you want to meet with",
        window.location.href
      );
    });

    socket.on("createMessage", (message, userName) => {
      messages.innerHTML =
        messages.innerHTML +
        `<div class="message">
            <b><i class="far fa-user-circle"></i> <span> ${
              userName === user ? "me" : userName
            }</span> </b>
            <span>${message}</span>
        </div>`;
    });

  </script>
</html>



server

const express = require("express");

const app = express();

const server = require("http").Server(app);

const { v4: uuidv4 } = require("uuid");

app.set("view engine", "ejs");

const io = require("socket.io")(server, {
  cors: {
    origin: '*'
  }
});

const { ExpressPeerServer } = require("peer");
const peerServer = ExpressPeerServer(server, {
  debug: true,
});

app.use("/peerjs", peerServer);
app.use(express.static("public"));

app.get("/", (req, res) => {

  let _uuidv4 = uuidv4()

  console.log("connect: " + _uuidv4)

  res.redirect(`/${_uuidv4}`);

});

app.get("/:room", (req, res) => {

  console.log("connect key: " + req.params.room)

  res.render("room", { roomId: req.params.room });

});

io.on("connection", (socket) => {

  socket.on("join-room", ( roomId, userId, userName ) => {

    console.log("connect user:", roomId, userId, userName );

    socket.join(roomId);

    socket.to(roomId).emit("user-connected", userId);

    socket.on("message", (message) => {

      io.to(roomId).emit("createMessage", message, userName);

    });


  });

});


server.listen(3030);

  • Вопрос задан
  • 53 просмотра
Решения вопроса 1
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы
22 нояб. 2024, в 08:04
1 руб./за проект
22 нояб. 2024, в 06:06
1500 руб./в час
22 нояб. 2024, в 06:04
1 руб./за проект