<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Testing local audio capture playback causes "playing" event to fire</title>
    <script src="../resources/testharness.js"></script>
    <script src="../resources/testharnessreport.js"></script>
    <script src ="routines.js"></script>
    <script>
    var context = new AudioContext();
    var remoteStream;

    async function checkForHumBipBop(stream, previousResults, counter)
    {
        if (!previousResults)
            previousResults = {
                heardHum : false,
                heardBip : false,
                heardBop : false
        };
        if (!counter)
            counter = 1;
        else if (++counter > 4)
            return Promise.resolve(false);
        results = await analyseAudio(stream, 1000, context);
        previousResults.heardHum |= results.heardHum;
        previousResults.heardBip |= results.heardBip;
        previousResults.heardBop |= results.heardBop;
        if (previousResults.heardHum && previousResults.heardBip && previousResults.heardBop)
            return Promise.resolve(true);
        var results = await checkForHumBipBop(stream, previousResults, counter);
        return results;
    }

    promise_test((test) => {
        if (window.testRunner)
            testRunner.setUserMediaPermission(true);

        return navigator.mediaDevices.getUserMedia({audio: true}).then((stream) => {
            return new Promise((resolve, reject) => {
                createConnections((firstConnection) => {
                    firstConnection.addTrack(stream.getAudioTracks()[0], stream);
                }, (secondConnection) => {
                    secondConnection.ontrack = (event) => { resolve(event.streams[0]); };
                });
                setTimeout(() => reject("Test timed out"), 5000);
            });
        }).then((stream) => {
            return checkForHumBipBop(stream);
        }).then((results) => {
            assert_true(results, "heard hum bip bop");
        }).then(() => {
            return context.close();
        });
    }, "Basic audio playback through a peer connection");
    </script>
</head>
<body>
</body>
</html>
