有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个.wav文件。我想从声音文件中获取PCM数据,这样我就可以从声音中获取单个数据块并对其进行处理

但我不知道怎么做。有人能告诉我怎么做吗? 到目前为止,我已经做到了:

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) {

        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    这可以通过Java SoundAPI完成

    • 使用AudioSystem从文件中获取AudioInputStream
    • 查询流中的AudioFormat
    • 创建一个byte[]以适合该格式。例如,8位单声道是byte[1]。16位立体声是byte[4]
    • byte[]的块读取流,它将一帧一帧地包含声音
    • 继续进行进一步处理
  2. # 2 楼答案

    下面是一个使用^{}包的完整工作示例。如果您需要音频格式的详细信息,可以通过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();
    }