简体   繁体   中英

Fetching audio file via Ajax

I need to fetch an audio file using Ajax and receive it in the form an array of bytes. My backend is on PHP.

Currently I am using

<?php 
echo  file_get_contents("./mainFile.mp3");
?>

This lets me return the audio file in the form an array of bytes. But how can I receive it in Javascript as a byte array. I referred this link on SO

But this does not seem to be the proper way. Can anyone please suggest something ???

Save a file named: raw_audio.php

<?php 
    echo  file_get_contents("./mainFile.mp3");
?>

Now load that php file from your ajax call.

$.ajax({
url:'raw_audio.php',
success: function(data)
{
 var raw=data;
}
});

You need to overrideMimeType() to "text/plain; charset=x-user-defined" like so:

$.ajax( {

        url: "php.php",

        beforeSend: function( xhr ){
        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
        },

        success: function( text ) {
        var i, l = text.length, bytes = [];

            for( i = 0; i < l; ++i ) {
            bytes.push( text.charCodeAt(i) & 0xFF );
            }
        console.log( bytes.length );
        }

});

Note that this is extremely futile, bit operations in javascript are extremely fast on strings+charCodeAt only. Even faster than on typed arrays, as I shockingly discovered in an application of mine.

The text/plain isn't important, but the charset is.

Try using the 'arraybuffer' response type:

request = new XMLHttpRequest();
request.responseType = "arraybuffer";
// ...

What you're looking to do is to read the file via ajax in a "binary" way. I just googled binary ajax and this is the first result that came up... not sure if it's useful... http://nagoon97.wordpress.com/2008/04/06/reading-binary-files-using-ajax/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM