从wav文件播放原始PCM字节(play a raw PCM byte from a wav fil

2019-09-30 05:29发布

我有与16位PCM编码WAV文件,我想将其转换为PCM短阵并播放audiotrack类原料阵列。 这是我做的:

        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();

该阵列可以播放,但问题是,当我摆弄原来的wav文件进行比较,我发现他们不输出相同的声音。 有人可以帮我这个问题? 先感谢您!

Answer 1:

你必须寻求实际的音频文件中的数据,以获得音频采样看到http://en.wikipedia.org/wiki/WAV或https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ 。

16位单声道的8kHz @一秒将8000 * 2个* 1个字节= 16000个字节



文章来源: play a raw PCM byte from a wav file