WebRTC getStat() API Set UP

后端 未结 1 1658
囚心锁ツ
囚心锁ツ 2020-12-31 20:24

I am trying to use getStat() from WebRTC\'s api to see if it provides any useful info measure latency and other video streaming data. The problem is that there\'s not much i

相关标签:
1条回答
  • 2020-12-31 21:04

    The following solution works for me.

    Creating peer connection

    pc = new RTCPeerConnection(pc_config, pc_constraints);
    

    Adding onaddstream handler

    pc.onaddstream = onRemoteStreamAdded;
    

    The handler itself

    var onRemoteStreamAdded = function(event) {
            attachMediaStream(remoteVideo, event.stream);
            remoteStream = event.stream;
    
            getStats(pc);
        };
    

    Pay attention on the getStats function called from the handler, the function is following

    function getStats(peer) {
        myGetStats(peer, function (results) {
            for (var i = 0; i < results.length; ++i) {
                var res = results[i];
                console.log(res);
            }
    
            setTimeout(function () {
                getStats(peer);
            }, 1000);
        });
    }
    

    The myGetStats function is a wrapper to make it possible universal in different browsers;

    function myGetStats(peer, callback) {
        if (!!navigator.mozGetUserMedia) {
            peer.getStats(
                function (res) {
                    var items = [];
                    res.forEach(function (result) {
                        items.push(result);
                    });
                    callback(items);
                },
                callback
            );
        } else {
            peer.getStats(function (res) {
                var items = [];
                res.result().forEach(function (result) {
                    var item = {};
                    result.names().forEach(function (name) {
                        item[name] = result.stat(name);
                    });
                    item.id = result.id;
                    item.type = result.type;
                    item.timestamp = result.timestamp;
                    items.push(item);
                });
                callback(items);
            });
        }
    };
    

    Every second it will get statistics and print raw object into console log. You can parse the log and then change the code, getting necessary object's field.

    0 讨论(0)
提交回复
热议问题