简体   繁体   English

如何从 wav 文件中获取 PCM 数据?

[英]How to get PCM data from a wav file?

I have a .wav file.我有一个.wav文件。 I want to get the PCM data from that sound file, so that I can get the individual data chunks from the sound and process it.我想从该声音文件中获取 PCM 数据,以便我可以从声音中获取各个数据块并对其进行处理。

But I don't know how to do it.但我不知道该怎么做。 Can anyone tell me how to do it?谁能告诉我怎么做? I have done this so far:到目前为止,我已经这样做了:

public class test
{

    static int frameSample;
    static int timeofFrame;
    static int N;
    static int runTimes;
    static int bps;
    static int channels;
    static double times;
    static int bufSize;
    static int frameSize;
    static int frameRate;
    static long length;

    public static void main(String[] args)
    {
        try
        {
            AudioInputStream ais = AudioSystem.getAudioInputStream(new File("music/audio.wav"));
            AudioInputStream a;
            int numBytes = ais.available();
            System.out.println("numbytes: "+numBytes);
            byte[] buffer = new byte[numBytes];
            byte[] buffer1=new byte[numBytes] ;
            int k=0;
            int count=0;
            while(count!=-1){
                count=ais.read(buffer, 0, numBytes);
            }
            long value = 0;

            for (int i = 0; i < buffer.length; i++)
            {
               value = ((long) buffer[i] & 0xffL) << (8 * i);
               System.out.println("value: "+value);
            }
        } catch(Exception e) {

        }
    }
}

This can be done with the Java Sound API. 这可以使用Java Sound API完成。

  • Use the AudioSystem to get an AudioInputStream from the file. 使用AudioSystem从文件中获取AudioInputStream
  • Query the stream for the AudioFormat . 查询AudioFormat的流。
  • Create a byte[] to suit the format. 创建一个byte[]以适应格式。 EG 8 bit mono is a byte[1] . EG 8位单声道是一个byte[1] 16 bit stereo is byte[4] . 16位立体声是byte[4]
  • Read the stream in chunks of the byte[] and it will contain the sound, frame by frame. byte[]块的形式读取流,它将逐帧包含声音。
  • Proceed with further processing.. 继续进行处理..

Here is a fully working example using the javax.sound.sampled package.这是一个使用javax.sound.sampled包的完整示例。 If you need details on the audio format you can get them via audioInputStream.getFormat() which will return a AudioFormat object.如果您需要有关音频格式的详细信息,您可以通过 audioInputStream.getFormat() 获取它们,这将返回一个AudioFormat对象。

public static byte[] getPcmByteArray(String filename) throws UnsupportedAudioFileException, IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream(65536);
    File inputFile = new File(filename);
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputFile);

    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = audioInputStream.read(buffer)) != -1) {
        baos.write(buffer, 0, bytesRead);
    }

    return baos.toByteArray();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM