Search code examples
javascriptjquerywebrtcpeerjs

PeerJS error when trying to call another peer: Failed to execute 'addStream' on 'RTCPeerConnection': parameter 1 is not of type 'MediaStream'


I am successfully establishing a connection between two peers using PeerJS but whenever I try passing a MediaStream object to the .call function I get this error:

Failed to execute 'addStream' on 'RTCPeerConnection': parameter 1 is not of type 'MediaStream'

Everything else works great, connection is indeed established, both peers receive messages from each other via the 'open' event. The only thing that doesn't work is the peer.call() function. The microphone is properly captured after requesting the permission to do so.

Am I making some kind of a mistake here? I'd appreciate any help. Thank you.

Here is my code:

var media;

jQuery(document).ready(function() {
  var peer = new Peer({
    key: 'xxxxxxxxxxxxx'
  });

  media = navigator.mediaDevices.getUserMedia({
    audio: true,
    video: false
  });

  peer.on('open', function(id) {
    console.log('My peer ID is: ' + id);
  });

  var conn = peer.connect(callID);

  conn.on('open', function() {
    // Receive messages
    conn.on('data', function(data) {
      console.log('Received', data);
    });

    // Send messages
    conn.send('Hello!');
  });

  console.log(typeof(media));

  var call = peer.call(callID, media);

  peer.on('error', function(err) {
    console.log(err);
  });
});

Solution

  • I'd be interested to see the output of console.log(typeof(media));.

    According to the MDN website, it seems that the following line will return a Promise instead of a MediaStream:

    media = navigator.mediaDevices.getUserMedia({audio: true, video: false});
    

    The following should work:

    var media;
    
    jQuery(document).ready(function() {
      var peer = new Peer({
        key: 'xxxxxxxxxxxxx'
      });
    
      navigator.mediaDevices.getUserMedia({
          audio: true,
          video: false
        })
        .then(function(mediaStream) {
          peer.on('open', function(id) {
            console.log('My peer ID is: ' + id);
          });
    
          var conn = peer.connect(callID);
    
          conn.on('open', function() {
            // Receive messages
            conn.on('data', function(data) {
              console.log('Received', data);
            });
    
            // Send messages
            conn.send('Hello!');
          });
    
          console.log(typeof(media));
    
          var call = peer.call(callID, mediaStream);
    
          peer.on('error', function(err) {
            console.log(err);
          });
        });
    });