1

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

Community
  • 1
  • 1
ping localhost
  • 479
  • 3
  • 22
  • Not sure what you mean by "array of bytes". What for? What does the JavaScript do with the data? – Pekka Nov 28 '11 at 18:37
  • Not sure of what you are trying to do here. Doesn't any reader will load and stream an audio file? Why loading it raw into PHP? – Fredy31 Nov 28 '11 at 18:40
  • Actually I wish to play the audio file using actionscript using the appendBytes function . I wish to feed this byte array fetched by AJAX to my actionscript class. P.S: I know the same thing can be done by directly fetching the audio by actionscript .. but the design of my site forces me to use JS for this purpose – ping localhost Nov 28 '11 at 18:44
  • does the link I posted not work for you? I glanced over their code... seems like it would do the trick. – Yevgeny Simkin Nov 28 '11 at 18:49

4 Answers4

1

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;
}
});
Nishchay Sharma
  • 1,314
  • 1
  • 9
  • 18
0

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.

Esailija
  • 138,174
  • 23
  • 272
  • 326
0

Try using the 'arraybuffer' response type:

request = new XMLHttpRequest();
request.responseType = "arraybuffer";
// ...
AshleysBrain
  • 22,335
  • 15
  • 88
  • 124
-1

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/

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236