Example usage for javax.sound.sampled SourceDataLine getBufferSize

List of usage examples for javax.sound.sampled SourceDataLine getBufferSize

Introduction

In this page you can find the example usage for javax.sound.sampled SourceDataLine getBufferSize.

Prototype

int getBufferSize();

Source Link

Document

Obtains the maximum number of bytes of data that will fit in the data line's internal buffer.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile"));
    //    stream = AudioSystem.getAudioInputStream(new URL(
    //      "http://hostname/audiofile"));

    AudioFormat format = stream.getFormat();
    if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(),
                format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2,
                format.getFrameRate(), true); // big endian
        stream = AudioSystem.getAudioInputStream(format, stream);
    }//from   w w w  .j  av  a 2 s. c  o m

    SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, stream.getFormat(),
            ((int) stream.getFrameLength() * format.getFrameSize()));
    SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
    line.open(stream.getFormat());
    line.start();

    int numRead = 0;
    byte[] buf = new byte[line.getBufferSize()];
    while ((numRead = stream.read(buf, 0, buf.length)) >= 0) {
        int offset = 0;
        while (offset < numRead) {
            offset += line.write(buf, offset, numRead - offset);
        }
    }
    line.drain();
    line.stop();
}