play a raw PCM byte from a wav file

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 16:27:26

问题


I have a wav file which was encoded with 16-bit PCM, I want to convert it to a PCM short array and play the raw array with audiotrack class. It is what I did:

        String fileName = "test.wav";
        File f = new File(baseDir + File.separator + fileName);
        InputStream is = null;
        try {
            is = new FileInputStream       (f);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
            BufferedInputStream     bis = new BufferedInputStream   (is, 8000);
            DataInputStream         dis = new DataInputStream       (bis);      //  Create a DataInputStream to read the audio data from the saved file
            short[] music = new short[(int) f.length()];
            int i = 0;                                                          //  Read the file into the "music" array
            try {
                while (dis.available() > 0)
                {
                    music[i] = dis.readShort();                                      //  This assignment does not reverse the order
                    i++;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.i("123",""+Arrays.toString(music));

            try {
                dis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }        

            at=new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, 8000 /* 1 second buffer */,
                    AudioTrack.MODE_STREAM);
            at.write(music, 0, (int)f.length());
            at.play();

The array can be played, but the problem is that when I compare it with playing the original wav file, I found that they don't output the same sound. Can someone help me with this issue? Thank you in advance!


回答1:


You have to seek to the actual audio data in the file to get the audio sample see http://en.wikipedia.org/wiki/WAV or https://ccrma.stanford.edu/courses/422/projects/WaveFormat/.

One second of 16bit mono @ 8khz will be 8000 * 2 * 1 bytes = 16000 bytes



来源:https://stackoverflow.com/questions/16002372/play-a-raw-pcm-byte-from-a-wav-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!