/** * This class reads an audio file (AudioInputStream) for analysis */public class AudioBuffer { private AudioInputStream in = null; public float[] left, right; /** Creates a new instance of AudioBuffer * @param Number of frames to read at a time */ public AudioBuffer(AudioInputStream in) { this.in = in; } /** * Read 1024 frames from the input stream */ public boolean read() { return this.read(1024); } /** * Read up to frames number of frames from the input stream * @param Number of frames to read */ public boolean read(int frames) { int nBytesRead = 0; int framesize = in.getFormat().getFrameSize(); byte[] audioBytes = new byte[framesize * frames]; try { nBytesRead = in.read(audioBytes, 0, audioBytes.length); if(nBytesRead == -1) return false; int framesRead = nBytesRead / framesize; left = new float[framesRead]; right = new float[framesRead]; // TODO this is 16-bit only for(int i = 0; i < framesRead; i++) { if(in.getFormat().isBigEndian()) { left[i] = ( (audioBytes[i * framesize] << 8) | (audioBytes[i * framesize + 1] & 0xFF) ) / 32768.0F; right[i] = ( (audioBytes[i * framesize + 2] << 8) | (audioBytes[i * framesize + 3] & 0xFF) ) / 32768.0F; } else { left[i] = ( (audioBytes[i * framesize] & 0xFF) | (audioBytes[i * framesize + 1] << 8) ) / 32768.0F; right[i] = ( (audioBytes[i * framesize + 2] & 0xFF) | (audioBytes[i * framesize + 3] << 8) ) / 32768.0F; } } } catch (IOException ex) { ex.printStackTrace(); return false; } return true; }}public class AudioBufferTest { private AudioBuffer mp3 = null; private Vector<Point.Double> wave = new Vector<Point.Double>(); public static void main(String args[]) { // Lots of lines to read and decode and mp3 file, could be used with an WAV file directly File f = new File("my.mp3"); AudioInputStream in = AudioSystem.getAudioInputStream(f); AudioFormat inFormat = in.getFormat(); AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, inFormat.getSampleRate(), 16, inFormat.getChannels(), inFormat.getChannels() * 2, inFormat.getSampleRate(), false); DecodedMpegAudioInputStream audioInputStream = new DecodedMpegAudioInputStream(decodedFormat, in); mp3 = new AudioBuffer(audioInputStream); System.out.print("Reading file..."); // I plan to use this vector to draw the waveform later while(mp3.read()) for (int i = 0; i < mp3.left.length - 1; i++) wave.add(new Point.Double(mp3.left[i], mp3.right[i])); // Here the heap space ends }}