如何发送AJAX POST请求并在响应中播放音频? [英] How to send AJAX POST request and play the audio in the response?

查看:40
本文介绍了如何发送AJAX POST请求并在响应中播放音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个用户可以单击按钮的应用程序,它将数据发送到服务器.然后,服务器根据请求中的数据(很可能是POST)计算音频,然后将WAV文件返回到浏览器.

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.

我已经建立了接受发布请求并使用wav文件进行响应的部分,但是我不知道如何在JS中发送请求并向用户播放响应.

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

推荐答案

类似的东西会起作用吗?

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>

get.php 只是打印音频文件链接.请注意,我没有得到任何WAV文件,因此无法对此进行测试.

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'; ?>

我上面打印的音频是30分钟的文件,大小约为13mb.我的互联网速度不够快,无法在一两秒钟内加载整个文件,但是它可以立即播放.

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.

这篇关于如何发送AJAX POST请求并在响应中播放音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆