Graphing wav file in java

前端 未结 1 1122
北恋
北恋 2020-12-22 09:15

I have been searching for this but none seems to answer my question. I have been trying to graph/plot a wav file by this:

int result = 0;
try {
    result =          


        
相关标签:
1条回答
  • 2020-12-22 09:54

    The first thing you need to do is read the samples of the file, this will give you the min/max ranges of the waveform (sound wave)...

        File file = new File("...");
        AudioInputStream ais = null;
        try {
            ais = AudioSystem.getAudioInputStream(file);
            int frameLength = (int) ais.getFrameLength();
            int frameSize = (int) ais.getFormat().getFrameSize();
            byte[] eightBitByteArray = new byte[frameLength * frameSize];
    
            int result = ais.read(eightBitByteArray);
    
            int channels = ais.getFormat().getChannels();
            int[][] samples = new int[channels][frameLength];
    
            int sampleIndex = 0;
            for (int t = 0; t < eightBitByteArray.length;) {
                for (int channel = 0; channel < channels; channel++) {
                    int low = (int) eightBitByteArray[t];
                    t++;
                    int high = (int) eightBitByteArray[t];
                    t++;
                    int sample = getSixteenBitSample(high, low);
                    samples[channel][sampleIndex] = sample;
                }
                sampleIndex++;
            }
    
        } catch (Exception exp) {
    
            exp.printStackTrace();
    
        } finally {
    
            try {
                ais.close();
            } catch (Exception e) {
            }
    
        }
    
    //...
    
    protected int getSixteenBitSample(int high, int low) {
        return (high << 8) + (low & 0x00ff);
    } 
    

    Then you would need to determine the min/max values, the next example simply checks for channel 0, but you could use the same concept to check all the available channels...

        int min = 0;
        int max = 0;
        for (int sample : samples[0]) {
    
            max = Math.max(max, sample);
            min = Math.min(min, sample);
    
        }
    

    FYI: It would be more efficient to populate this information when you read the file

    Once you have this, you can model the samples...but that would depend on framework you intend to use...

    0 讨论(0)
提交回复
热议问题