How to send AJAX POST request and play the audio in the response?

10,342

Will something like this work?

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

    <audio controls>
        <source id="source" src="" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $.ajax({
            url: 'get.php',
            data: { attr1: 'value1' },
            success: function( data ) {
                console.log(data);
                $('audio #source').attr('src', data);
                $('audio').get(0).load();
                $('audio').get(0).play();
            }
        });
    </script>
</body>
</html>

While the get.php just prints the audio file link. Note that I didn't get any WAV file so can't test on that.

<?php echo 'http://junaidahmed.io/w/audio.mp3'; ?>

That audio I'm printing above is a 30 minute and about 13mb file size. My internet is not fast enough to load the whole file in a second or two and yet it plays right away.

Share:
10,342
ginkoid
Author by

ginkoid

Updated on July 18, 2022

Comments

  • ginkoid
    ginkoid almost 2 years

    I am building an app where the user can click a button, and it sends data to the server. The server then computes audio based on the data in the request (most likely a POST), and returns a WAV file to the browser.

    I have already built the part with accepting a post request and responding with the wav file, but I can't figure out how to send the request in JS and to play the response to the user.

    Also, the playing of the audio must start (almost) as the first byte comes in, as the audio files are quite large, and the user can't just wait for the request to be completed.

    I am also open to suggestions changing how the server sends the file: the server is made in flask