8.7 GetStats Example
Consider the case where the user is experiencing bad sound and the application wants to determine if the cause of it is packet loss. The following example code might be used:
async function gatherStats(pc) {
try {
const [sender] = pc.getSenders();
const baselineReport = await sender.getStats();
await new Promise(resolve => setTimeout(resolve, aBit)); // wait a bit
const currentReport = await sender.getStats();
// compare the elements from the current report with the baseline
for (const now of currentReport.values()) {
if (now.type != 'outbound-rtp') continue;
// get the corresponding stats from the baseline report
const base = baselineReport.get(now.id);
if (!base) continue;
const remoteNow = currentReport.get(now.remoteId);
const remoteBase = baselineReport.get(base.remoteId);
const packetsSent = now.packetsSent - base.packetsSent;
const packetsReceived = remoteNow.packetsReceived -
remoteBase.packetsReceived;
const fractionLost = (packetsSent - packetsReceived) / packetsSent;
if (fractionLost > 0.3) {
// if fractionLost is > 0.3, we have probably found the culprit
}
}
} catch (err) {
console.error(err);
}
}