Problem with reading wav file with Java

这一生的挚爱 提交于 2019-12-11 07:19:35

问题


I use that API to read wav file at Java: Reading and Writing Wav Files in Java

I read a wav file with Java and want to put all the values into an arraylist. I wrote:

// Open the wav file specified as the first argument
     WavFile wavFile = WavFile.openWavFile(fileToRemoveSilence);
     List<Double> allBuffer = new ArrayList<Double>();

 ....
     do {
        // Read frames into buffer
        framesRead = wavFile.readFrames(buffer, 50);
        for (double aBuffer : buffer) {
           allBuffer.add(aBuffer);
        }

     } while (framesRead != 0);

When I check the size of allBuffer at debugger it says:

74700

However at the code it whe I use:

wavFile.display();

the output of it:

....
... Frames: 74613
....

My allbuffer is bigger than frames as displayed by that API. How it comes?

PS: My previous questions about this:

Reading wav file in Java

How to divide a wav file into 1 second pieces with Java?

PS2: I fixed the bugs however when I run the program I get that error sometimes: What may be the problem?

java.lang.InterruptedException
at java.lang.Object.wait(Native Method)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134)
at sun.java2d.Disposer.run(Disposer.java:127)
at java.lang.Thread.run(Thread.java:662)

Exception while removing reference: java.lang.InterruptedException


回答1:


you need to account for framesRead when copying from the buffer into your list. on the last call, you are copying more doubles than you actually read from the file. (i.e. exactly like the example code in your first link).




回答2:


I think you want something like this:

// Open the wav file specified as the first argument
     WavFile wavFile = WavFile.openWavFile(fileToRemoveSilence);
     List<double[]> allBuffer = new List<double[]>();

    int bufferSize = 44100; // 1 second, probably
    double[] buffer;


 ....
     do {
        // Read frames into buffer

        buffer = new double[bufferSize];
        framesRead = wavFile.readFrames(buffer, bufferSize);
        if (framesRead == bufferSize)
        {
            allBuffer.add(buffer);
        }
        else
        {
            double[] crippleBuffer = new double[framesRead];
            Array.Copy(buffer, crippleBuffer, framesRead);
            allBuffer.add(crippleBuffer);
            break;
        }

     } 

This will leave you with a List of 1-second double[] arrays of samples (actually, the last array will be somewhat less than a full second). You can then iterate through this collection of arrays and turn each one into a separate WAV file.



来源:https://stackoverflow.com/questions/5983457/problem-with-reading-wav-file-with-java

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