gpt4 book ai didi

javascript - RTCPeerConnection.createOffer "promise"用法

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:02:54 25 4
gpt4 key购买 nike

我最近在学习 WebRTC,在这里发现了“promise”的用法 (https://github.com/mdn/samples-server/blob/master/s/webrtc-simple-datachannel/main.js)。

localConnection.createOffer()
.then(offer => localConnection.setLocalDescription(offer))
.then(() => remoteConnection.setRemoteDescription(localConnection.localDescription))
.then(() => remoteConnection.createAnswer())
.then(answer => remoteConnection.setLocalDescription(answer))
.then(() => localConnection.setRemoteDescription(remoteConnection.localDescription))
.catch(handleCreateDescriptionError);

localConnection 和 removeConnection 是 RTCPeerConnection 对象。从这里https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection ,

createOffer:

void createOffer(RTCSessionDescriptionCallback successCallback, RTCPeerConnectionErrorCallback failureCallback, optional MediaConstraints constraints);

createOffer 有 3 个参数。但是为什么上面的代码没有参数呢?参数在哪里?

最佳答案

因为 API 已通过 promises 实现了现代化,并且文档已过时。

之前:

pc.createOffer(onSuccess, onFailure, options);

After :

pc.createOffer(options).then(onSuccess, onFailure)

其中 options 是可选的。由于 adapter.js,这应该适用于所有支持 WebRTC 的浏览器polyfill(也可以在 Firefox 中原生运行)。

ES6 => 箭头函数适用于 Firefox 和 Chrome 45,您可以在其中尝试 this :

var pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

var add = (pc, can) => can && pc.addIceCandidate(can).catch(failed);
pc1.onicecandidate = e => add(pc2, e.candidate);
pc2.onicecandidate = e => add(pc1, e.candidate);
pc2.onaddstream = e => v2.srcObject = e.stream;
pc1.oniceconnectionstatechange = e => log(pc1.iceConnectionState);

var start = () =>
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => pc1.addStream(v1.srcObject = stream))
.then(() => pc1.createOffer()).then(d => pc1.setLocalDescription(d))
.then(() => pc2.setRemoteDescription(pc1.localDescription))
.then(() => pc2.createAnswer()).then(d => pc2.setLocalDescription(d))
.then(() => pc1.setRemoteDescription(pc2.localDescription))
.catch(failed);

var log = msg => div.innerHTML += "<p>" + msg + "</p>";
var failed = e => log(e +", line "+ e.lineNumber);
<video id="v1" height="120" width="160" autoplay></video>
<video id="v2" height="120" width="160" autoplay></video><br>
<button onclick="start()">Start!</button><div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

注意 Chrome 45 用户,使用fiddle ,因为相同的代码在 stackoverflow 代码片段中不起作用!

关于javascript - RTCPeerConnection.createOffer "promise"用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com