如何在WebRTC中的MediaStream中添加Track

时间:2016-02-19 11:28:41

标签: webrtc microphone audiotrack mediastream

我正在使用webrtc与同行之间进行通信。我不想为旧生成的流添加新轨道,因为我不想在音频通信期间为用户提供切换麦克风的功能。我正在使用的代码是,

让“pc”成为通过其进行音频通信的peerConnection对象。 “newStream”是使用新选择的麦克风设备从getUserMedia函数获取的新生成的MediaStream。

            var localStreams = pc.getLocalStreams()[0];
            localStreams.removeTrack(localStreams.getAudioTracks()[0]);


            var audioTrack = newStream.getAudioTracks()[0];
            localStreams.addTrack(audioTrack);

他们以任何方式新添加的曲目开始到达另一个先前连接的同伴而不再向他提供整个SDP吗?

在这种交换媒体设备的情况下使用的优化方式是什么,即在对等体之间已建立连接的情况下使用麦克风?

1 个答案:

答案 0 :(得分:7)

更新: 靠近底部的工作示例。

由于规范不断发展,这在很大程度上取决于您目前使用的浏览器。

the specification和Firefox中,对等连接现在基本上是基于跟踪的,并且不依赖于本地流关联。您有var sender = pc.addTrack(track, stream)pc.removeTrack(sender),甚至sender.replaceTrack(track),后者根本不涉及重新谈判。

在Chrome中,您仍然只有pc.addStreampc.removeStream,并且从本地流中删除曲目会导致将其停止发送,但是将其添加回来却无效。我很幸运删除并重新添加整个流到对等连接,然后重新协商。

不幸的是,使用adapter.js在这里没有用,因为addTrack对于填充来说很棘手。

重新协商

重新谈判没有重新开始。您所需要的只是:

pc.onnegotiationneeded = e => pc.createOffer()
  .then(offer => pc.setLocalDescription(offer))
  .then(() => signalingChannel.send(JSON.stringify({ "sdp": pc.localDescription }));
  .catch(failed);

添加此功能后,对等连接会在需要时使用您的信令通道自动重新协商。这甚至取代了你现在正在做的createOffer和朋友的电话,这是一场净胜利。

有了这个,您可以在实时连接期间添加/删除曲目,它应该“正常工作”。

如果这不够顺利,你甚至可以pc.createDataChannel("yourOwnSignalingChannel")

实施例

以下是所有这些示例(在Chrome中使用https fiddle):

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

var dc, sc, pc = new RTCPeerConnection(config), live = false;
pc.onaddstream = e => v2.srcObject = e.stream;
pc.ondatachannel = e => dc? scInit(sc = e.channel) : dcInit(dc = e.channel);

var streams = [];
var haveGum = navigator.mediaDevices.getUserMedia({fake:true, video:true})
.then(stream => streams[1] = stream)
.then(() => navigator.mediaDevices.getUserMedia({ video: true }))
.then(stream => v1.srcObject = streams[0] = stream);

pc.oniceconnectionstatechange = () => update(pc.iceConnectionState);

var negotiating; // Chrome workaround
pc.onnegotiationneeded = () => {
  if (negotiating) return;
  negotiating = true;
  pc.createOffer().then(d => pc.setLocalDescription(d))
  .then(() => live && sc.send(JSON.stringify({ sdp: pc.localDescription })))
  .catch(log);
};
pc.onsignalingstatechange = () => negotiating = pc.signalingState != "stable";

function scInit() {
  sc.onmessage = e => wait(signalingDelayMs).then(() => { 
    var msg = JSON.parse(e.data);
    if (msg.sdp) {
      var desc = new RTCSessionDescription(JSON.parse(e.data).sdp);
      if (desc.type == "offer") {
        pc.setRemoteDescription(desc).then(() => pc.createAnswer())
        .then(answer => pc.setLocalDescription(answer)).then(() => {
          sc.send(JSON.stringify({ sdp: pc.localDescription }));
        }).catch(log);
      } else {
        pc.setRemoteDescription(desc).catch(log);
      }
    } else if (msg.candidate) {
      pc.addIceCandidate(new RTCIceCandidate(msg.candidate)).catch(log);
    }
  }).catch(log);
}

function dcInit() {
  dc.onopen = () => {
    live = true; update("Chat:"); chat.disabled = false; chat.select();
  };
  dc.onmessage = e => log(e.data);
}

function createOffer() {
  button.disabled = true;
  pc.onicecandidate = e => {
    if (live) {
      sc.send(JSON.stringify({ "candidate": e.candidate }));
    } else if (!e.candidate) {
      offer.value = pc.localDescription.sdp;
      offer.select();
      answer.placeholder = "Paste answer here";
    }
  };
  dcInit(dc = pc.createDataChannel("chat"));
  scInit(sc = pc.createDataChannel("signaling"));
};

offer.onkeypress = e => {
  if (e.keyCode != 13 || pc.signalingState != "stable") return;
  button.disabled = offer.disabled = true;
  var obj = { type:"offer", sdp:offer.value };
  pc.setRemoteDescription(new RTCSessionDescription(obj))
  .then(() => pc.createAnswer()).then(d => pc.setLocalDescription(d))
  .catch(log);
  pc.onicecandidate = e => {
    if (e.candidate) return;
    if (!live) {
      answer.focus();
      answer.value = pc.localDescription.sdp;
      answer.select();
    } else {
      sc.send(JSON.stringify({ "candidate": e.candidate }));
    }
  };
};

answer.onkeypress = e => {
  if (e.keyCode != 13 || pc.signalingState != "have-local-offer") return;
  answer.disabled = true;
  var obj = { type:"answer", sdp:answer.value };
  pc.setRemoteDescription(new RTCSessionDescription(obj)).catch(log);
};

chat.onkeypress = e => {
  if (e.keyCode != 13) return;
  dc.send(chat.value);
  log("> " + chat.value);
  chat.value = "";
};

function addTrack() {
  pc.addStream(streams[0]);
  flipButton.disabled = false;
  removeAddButton.disabled = false;
}

var flipped = 0;
function flip() {
  pc.getSenders()[0].replaceTrack(streams[flipped = 1 - flipped].getVideoTracks()[0])
  .catch(log);
}

function removeAdd() {
  if ("removeTrack" in pc) {
    pc.removeTrack(pc.getSenders()[0]);
    pc.addStream(streams[flipped = 1 - flipped]);
  } else {
    pc.removeStream(streams[flipped]);
    pc.addStream(streams[flipped = 1 - flipped]);
  }
}

var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
var update = msg => div2.innerHTML = msg;
var log = msg => div.innerHTML += msg + "<br>";
<video id="v1" width="120" height="90" autoplay muted></video>
<video id="v2" width="120" height="90" autoplay></video><br>
<button id="button" onclick="createOffer()">Offer:</button>
<textarea id="offer" placeholder="Paste offer here"></textarea><br>
Answer: <textarea id="answer"></textarea><br>
<button id="button" onclick="addTrack()">AddTrack</button>
<button id="removeAddButton" onclick="removeAdd()" disabled>Remove+Add</button>
<button id="flipButton" onclick="flip()" disabled>ReplaceTrack (FF only)</button>
<div id="div"><p></div><br>
<table><tr><td><div id="div2">Not connected</div></td>
  <td><input id="chat" disabled></input></td></tr></table><br>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

<强>说明:

没有涉及服务器,所以点击Offer,然后在两个标签之间手动切换'n'paste offer并回答(粘贴后点击ENTER键)。

完成后,您可以通过数据频道进行聊天,然后点击addTrack将视频添加到另一方。

然后,您可以使用Remove + AddreplaceTrack (FF only)远程切换显示的视频(如果您有要使用的辅助相机,请在Chrome中修改小提琴。)

重新谈判现在都在数据通道上发生(不再是'cut'n'paste)。