Using AudioTrack in Android to play a WAV file

后端 未结 7 975
别跟我提以往
别跟我提以往 2020-12-01 05:50

I\'m working with Android, trying to make my AudioTrack application play a Windows .wav file (Tada.wav). Frankly, it shouldn\'t be this hard, but I\'m hearing a lot of stra

7条回答
  •  星月不相逢
    2020-12-01 06:09

    I stumbled on the answer (frankly, by trying &^@! I didn't think would work), in case anybody's interested... In my original code (which is derived from the example in the link in the original post), the data is read from the file like so:

        InputStream             is  = new FileInputStream       (file);
        BufferedInputStream     bis = new BufferedInputStream   (is, 8000);
        DataInputStream         dis = new DataInputStream       (bis);      //  Create a DataInputStream to read the audio data from the saved file
    
        int i = 0;                                                          //  Read the file into the "music" array
        while (dis.available() > 0)
        {
            music[i] = dis.readShort();                                     //  This assignment does not reverse the order
            i++;
        }
    
        dis.close();                                                        //  Close the input stream
    

    In this version, music[] is array of SHORTS. So, the readShort() method would seem to make sense here, since the data is 16-bit PCM... However, on the Android that seems to be the problem. I changed that code to the following:

         music=new byte[(int) file.length()];//size & length of the file
        InputStream             is  = new FileInputStream       (file);
        BufferedInputStream     bis = new BufferedInputStream   (is, 8000);
        DataInputStream         dis = new DataInputStream       (bis);      //  Create a DataInputStream to read the audio data from the saved file
    
        int i = 0;                                                          //  Read the file into the "music" array
        while (dis.available() > 0)
        {
            music[i] = dis.readByte();                                      //  This assignment does not reverse the order
            i++;
        }
    
        dis.close();                                                        //  Close the input stream
    

    In this version, music[] is an array of BYTES. I'm still telling the AudioTrack that it's 16-bit PCM data, and my Android doesn't seem to have a problem with writing an array of bytes into an AudioTrack thus configured... Anyway, it finally sounds right, so if anyone else wants to play Windows sounds on their Android, for some reason, that's the solution. Ah, Endianness......

    R.

提交回复
热议问题