How would one get the values from a wav file. Would you use a data stream or audio stream?

Thanks,

jakx12.

Dani AI

Generated

As is trying to visualise a waveform and, as pointed out, the needed values depend on the use case, the usual Java approach is to read PCM samples from an AudioInputStream, convert them to numeric amplitudes, and then map indices to time using the sample rate.

A short workflow:

  • Open the file with AudioSystem.getAudioInputStream and inspect AudioFormat (sample rate, bits per sample, channels, endianess).
  • If the stream is not PCM_SIGNED, request a converted stream via AudioSystem.getAudioInputStream(targetFormat, ais).
  • Read bytes in frame-sized chunks. For interleaved multi-channel WAVs, samples are arranged per frame (channel0,channel1,...).
  • Convert bytes to numeric samples (8-bit PCM is unsigned; 16-bit is signed; account for endianness). Normalize samples to [-1.0,1.0] for plotting and compute time = sampleIndex / sampleRate. Downsample or compute min/max per pixel column for large files to keep the UI responsive.

Example (16-bit little-endian mono snippet):

try (AudioInputStream ais = AudioSystem.getAudioInputStream(new File("in.wav"))) {
    AudioFormat fmt = ais.getFormat();
    int frameSize = fmt.getFrameSize();
    byte[] buf = new byte[frameSize * 4096];
    int read;
    while ((read = ais.read(buf)) > 0) {
        for (int off = 0; off + 1 < read; off += frameSize) {
            int low = buf[off] & 0xff;
            int high = buf[off + 1] & 0xff;
            short sample = (short) ((high << 8) | low); // little-endian
            float norm = sample / 32768f;
            // store norm for plotting
        }
    }
}

For details on Java sound classes and format fields see the Java docs for AudioInputStream and AudioFormat, and for container/endianness background see the WAV description.

AudioInputStream
AudioFormat
WAV (Wikipedia)

Recommended Answers

All 4 Replies

Depends what values you want and for what usage.

I want to be able to plot it. I heard wav files contain amplitudes and stuff and i wanted to plot that over time.

Depends what values you want and for what usage.

I want to be able to plot it. I heard wav files contain amplitudes and stuff and i wanted to plot that over time.

bump..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.