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

半城伤御伤魂 提交于 2021-02-07 04:14:13

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/44896667/how-to-send-ajax-post-request-and-play-the-audio-in-the-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!