locked
how to convert audio file to bytestream in windows store javascript app

    Question

  • Hi Guys,

    I have a window store app build using VS 2012 express and PhoneGap2.2.0.

    In that i am using Windows.Storage.Pickers.FileOpenPicker(); to pick audio files.

    Now i need to read the selected file into byte stream and send it to a web service.

    Please advice how i can convert audio file into bytestream using javascript. If its not possible with javascript then can i do this in a c# project and include that into my javascript app

    thanks

    Amit

    • Changed type Song Tian Thursday, December 27, 2012 10:18 AM
    Thursday, December 20, 2012 10:35 AM

Answers

  • Hi Amit,

    If you have already got the DataReader object from the file, then you can direclty call DataReader.readBytes method to retrieve bytes from the underlying buffer stream.

    #DataReader.ReadBytes | readBytes method (Windows)
    http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.streams.datareader.readbytes.aspx?cs-save-lang=1&cs-lang=javascript#code-snippet-1

    here is simple example:

     function readTestFileBytes() {
            Windows.Storage.KnownFolders.musicLibrary.getFileAsync("test.txt").then(
                function (file) {
                    return Windows.Storage.FileIO.readBufferAsync(file);
                }
            ).done(
                function (buffer) {
                    var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
                    var arrBytes = new Uint8Array(buffer.length);
                    dataReader.readBytes(arrBytes);
                    // now the arrBytes contains all the raw bytes from the buffer/file stream
                  
                    dataReader.close();
                },
                function (error) {
                    var outputDiv = document.getElementById("output");
                    outputDiv.innerHTML = "error: " + error;
                }
            );
        }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Song Tian Thursday, December 27, 2012 10:18 AM
    Wednesday, December 26, 2012 6:50 AM
    Moderator

All replies

  • Hi Amit,

    After you get the reference to a certain file through File picker component, you can use the "Windows.Storage.FileIO" class to retrieve a buffer object from the file reference:


    #FileIO.ReadBufferAsync | readBufferAsync method (Windows)
    http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.fileio.readbufferasync.aspx


    and then, you can create a DataReader object from the buffer and read data from the file buffer(such as integer, boolean, string or raw bytes):


    #DataReader class (Windows)
    http://msdn.microsoft.com/en-us/library/windows/apps/br208119.aspx


    You can refer to the "File Access" sample in the sample collection for more ideas:


    #File access sample
    http://code.msdn.microsoft.com/windowsapps/File-access-sample-d723e597


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, December 24, 2012 9:36 AM
    Moderator
  • Hi Steven,

    Thanks for the reply.

    Do i need to do all this in a C# plugin or can this be done in javascript?

    My app is a PhoneGap app

    Please advise


    Thanks

    Amit


    • Edited by Amit Sood Monday, December 24, 2012 9:42 AM
    Monday, December 24, 2012 9:39 AM
  • Hi Amit,

    All the class/method I referenced are winRT specific which is fully supported in javascript. Also, the SDK "File access sample" also has javascript version. :)

    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, December 24, 2012 9:49 AM
    Moderator
  • Hi Steven,

    I tried as you advised, but i am getting buffer.length as 0. Here's the complete code.

    i have a '.amr' in my music library, which i am picking using file open picker.


     function bufferFile() {         var openPicker = new Windows.Storage.Pickers.FileOpenPicker();        openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary;        openPicker.fileTypeFilter.replaceAll([".amr"]);        openPicker.pickSingleFileAsync().then(function (file) {            if (file) {                SdkSample.sampleFile = file;                Windows.Storage.FileIO.readBufferAsync(file).then(function (buffer) {                                  var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);                    var fileContent = dataReader.readString(buffer.length);                    console.log('~~~~~~~~~~~~~~~~~~ ' + fileContent);                    dataReader.close();                },                // Handle errors with an error function                function (error) {                    alert('12');                });            } else {                alert('2134');            }        });

    Please help

    thanks

    Amit

    Monday, December 24, 2012 11:31 AM
  • Hi Steven,

    I figured out that it ain't working with .amr and worked with .wav file. Now the code looks like below. Its giving be an object of type IBuffer. How to i read from it to get the bytes?

      var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
            openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary;
            openPicker.fileTypeFilter.replaceAll([".amr", ".txt", ".wav"]);
         
            openPicker.pickSingleFileAsync().done(function (file) {
                if (file) {
                    SdkSample.sampleFile = file;
                    Windows.Storage.FileIO.readBufferAsync(file).done(function (buffer) {
                        var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
                        var fileContent = dataReader.readBuffer(buffer.length);
                        console.log('~~~~~~~~~~~~~~~~~~ ' + fileContent.length);
                        dataReader.close();
                    },
                    // Handle errors with an error function
                    function (error) {
                        alert('12');
                    });
                } else {
                    alert('2134');
                }
            });

    Wednesday, December 26, 2012 5:38 AM
  • Hi Amit,

    If you have already got the DataReader object from the file, then you can direclty call DataReader.readBytes method to retrieve bytes from the underlying buffer stream.

    #DataReader.ReadBytes | readBytes method (Windows)
    http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.streams.datareader.readbytes.aspx?cs-save-lang=1&cs-lang=javascript#code-snippet-1

    here is simple example:

     function readTestFileBytes() {
            Windows.Storage.KnownFolders.musicLibrary.getFileAsync("test.txt").then(
                function (file) {
                    return Windows.Storage.FileIO.readBufferAsync(file);
                }
            ).done(
                function (buffer) {
                    var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
                    var arrBytes = new Uint8Array(buffer.length);
                    dataReader.readBytes(arrBytes);
                    // now the arrBytes contains all the raw bytes from the buffer/file stream
                  
                    dataReader.close();
                },
                function (error) {
                    var outputDiv = document.getElementById("output");
                    outputDiv.innerHTML = "error: " + error;
                }
            );
        }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Song Tian Thursday, December 27, 2012 10:18 AM
    Wednesday, December 26, 2012 6:50 AM
    Moderator
  • Hi Steven,

    Thanks, i am able to get the bytes now. But i need to post them to a third party web service. I ab able to do this in C# but struggling to do it in javascript.

    This is my C# code. I am able to do its equivalent in javascript till the line in 'bold'. but how do i post it.  


            public Echo()
            {
                Stream postStream = null;
                FileStream audioFileStream = null;
                audioFileStream = new FileStream("c:/samplewav.wav", FileMode.Open, FileAccess.Read);
                BinaryReader reader = new BinaryReader(audioFileStream);
                byte[] binaryData = reader.ReadBytes((int)audioFileStream.Length);
                reader.Close();
                audioFileStream.Close();

                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty + this.fqdn + "/rest/2/");
                httpRequest.ContentLength = binaryData.Length;
                httpRequest.ContentType = "audio/wav";
                httpRequest.Accept = "application/json";
                httpRequest.Method = "POST";
                httpRequest.KeepAlive = true;
                postStream = httpRequest.GetRequestStream();
                postStream.Write(binaryData, 0, binaryData.Length);
                postStream.Close();
                HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse();
            }

    Thanks, you have been great.

    Amit


    • Edited by Amit Sood Thursday, December 27, 2012 9:03 AM
    Thursday, December 27, 2012 9:02 AM
  • Thanks for the reply Amit,

    Glad that you've made progress on this. regarding on the further question, would you mind creating a new thread and focus on the question in that one? Thus, we can close this one first so that further discussion (for other questions) are separated from the original question in this thread.

    Thank you!


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    Thursday, December 27, 2012 9:17 AM
    Moderator
  • Sure, i have create another thread, here is the link

    http://social.msdn.microsoft.com/Forums/en-US/winappswithhtml5/thread/40d10760-3bdf-4dae-8bdd-ddce127aea01

    I will close this now thanks

    Amit

    Thursday, December 27, 2012 9:25 AM