this.pc = new RTCPeerConnection(null);
this.pc.ontrack = (event) => {
this._mediaElement['srcObject'] = event.streams[0];
};
this.pc.addTransceiver('audio', {direction: 'recvonly'});
this.pc.addTransceiver('video', {direction: 'recvonly'});
this.sendChannel = this.pc.createDataChannel('keepalive');
this.sendChannel.onclose = this.onChannelClose.bind(this);
this.sendChannel.onopen = this.onChannelOpen.bind(this);
this.sendChannel.onmessage = this.onChannelMessage.bind(this);
this.pc.createOffer({
offerToReceiveVideo: !0,
offerToReceiveAudio: !0
}).then((offer) => {
return this.pc.setLocalDescription(offer).then(() => {
return offer;
});
}).then((offer) => {
return new Promise((resolve, reject) => {
this.HttpPost(url, window.btoa(offer.sdp)).then((res) => {
resolve(res);
}, function (rej) {
reject(rej);
});
});
}).then((answerSdp) => {
return this.pc.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: window.atob(answerSdp)
}));
}).then(() => {
this._isLoad = true;
}).catch((reason) => {
throw reason;
});
HttpPost(url, data) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
var respone = xhr.responseText;
xhr.onreadystatechange = new Function;
xhr = null;
resolve(respone);
}
};
xhr.open('POST', url.replace('webrtc', 'http'), true);
xhr.send(data);
});
}
this.pc.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: window.atob(answerSdp)
}));
的过程中需要徐亚与服务器保持连接,可以 sendChannel.send(msg)来保持持续拉流 。