智慧农业后台管理页面
guanqb
2022-09-03 e36ce8a4943cae5cd0cb46ea5373269e06eb9d56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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);
    }
}