class WebRtcPlayer {
|
/**
|
* WebRtc播放器
|
* @param {Element} ele
|
*/
|
constructor(ele) {
|
this.ele = ele;
|
// this.PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
|
this.PeerConnection = window.RTCPeerConnection;
|
|
}
|
Open(url) {
|
if(this.localpc){
|
this.Close();
|
}
|
this.localpc = new this.PeerConnection(null);
|
const AudioTransceiverInit = {
|
direction: 'recvonly',
|
sendEncodings: []
|
};
|
const VideoTransceiverInit = {
|
direction: 'recvonly',
|
sendEncodings: []
|
};
|
this.localpc.addTransceiver('audio', AudioTransceiverInit);
|
this.localpc.addTransceiver('video', VideoTransceiverInit);
|
let that = this;
|
this.localpc.ontrack = function (e) {
|
if (!that.localpc.stream) {
|
that.localpc.streamId = e.track.id;
|
that.localpc.stream = new MediaStream();
|
that.ele.srcObject = that.localpc.stream;
|
that.ele.muted = true;
|
that.ele.autoplay = true;
|
}
|
that.localpc.stream.addTrack(e.track);
|
}
|
|
this.localpc.createOffer()
|
.then(offer => this.localpc.setLocalDescription(offer))
|
.then(() => {
|
that.getSdp(url, this.localpc.localDescription.sdp, function (data) {
|
console.log("pullStreamRes:", data);
|
data = JSON.parse(data);
|
if (data.code != 0) return;
|
let anwser = {};
|
anwser.sdp = data.sdp;
|
anwser.type = 'answer';
|
that.localpc.setRemoteDescription(anwser).then(() => {
|
console.log("播放成功");
|
}).catch(e => {
|
console.error("播放错误:" + e);
|
});
|
});
|
})
|
.catch(e => "添加ICE候选人过程错误: " + e);
|
}
|
Close() {
|
if(this.localpc){
|
this.localpc.close();
|
this.localpc = null;
|
}
|
}
|
getSdp(url, body, success) {
|
let xhr = new XMLHttpRequest();
|
xhr.open('POST', url);
|
xhr.setRequestHeader('Content-Type', 'text/plain;charset=utf-8');
|
xhr.onreadystatechange = function () {
|
if (xhr.responseText.length < 1) return;
|
if (xhr.status === 200) {
|
success(xhr.responseText);
|
}
|
};
|
xhr.send(body);
|
}
|
}
|