Skip to content

Instantly share code, notes, and snippets.

@loriopatrick
Created February 19, 2014 22:12
Show Gist options
  • Save loriopatrick/9102762 to your computer and use it in GitHub Desktop.
Save loriopatrick/9102762 to your computer and use it in GitHub Desktop.
Get audio input
package audiosource;
import javax.sound.sampled.*;
import java.io.IOException;
import java.nio.ByteBuffer;
public class Listener {
public Listener() throws LineUnavailableException {
audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleRate, sampleSize,
channels, sampleSize / 8 * channels, sampleRate, true);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
if (!AudioSystem.isLineSupported(info)) {
throw new LineUnavailableException("Line is not supported: " + info.toString());
}
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(audioFormat, line.getBufferSize());
}
public float getSampleRate() {
return sampleRate;
}
private final AudioFormat audioFormat;
private final float sampleRate = 44100.0f;
private final int channels = 2;
private final int sampleSize = 16;
private final TargetDataLine line;
private AudioInputStream stream;
public void start() {
stream = new AudioInputStream(line);
line.start();
}
public double[] stop() throws IOException {
byte[] buffer = new byte[stream.available()];
if (stream.read(buffer) != buffer.length) {
throw new RuntimeException("available and received are not the same :(");
}
double[] res = new double[buffer.length / 2];
for (int i = 0; i < res.length; ++i) {
res[i] = ByteBuffer.wrap(buffer, i * 2, 2).getShort();
}
stream.close();
line.stop();
return res;
}
public void close() {
line.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment