Java examples for javax.sound.sampled:Audio
record audio
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; public class Main{ public static void record(AudioFormat sourceFormat, int seconds, OutputStream out) throws AudioUtil.Exception { _validateAudioFormat(sourceFormat); try {// w w w . ja v a 2s .co m DataLine.Info info = new DataLine.Info(TargetDataLine.class, sourceFormat); TargetDataLine line = (TargetDataLine) AudioSystem .getLine(info); line.open(sourceFormat); line.start(); int bufferSize = (int) sourceFormat.getSampleRate() * sourceFormat.getFrameSize(); byte buffer[] = new byte[bufferSize]; int i = 0; while (i < seconds) { int count = line.read(buffer, 0, buffer.length); if (count > 0) { out.write(buffer, 0, count); } i++; } line.close(); } catch (java.lang.Exception e) { throw new AudioUtil.Exception(e); } } public static void record(AudioFormat sourceFormat, ValueAccessor<Boolean> stopper, OutputStream out) throws AudioUtil.Exception { _validateAudioFormat(sourceFormat); try { DataLine.Info info = new DataLine.Info(TargetDataLine.class, sourceFormat); TargetDataLine line = (TargetDataLine) AudioSystem .getLine(info); line.open(sourceFormat); line.start(); int bufferSize = 256; byte buffer[] = new byte[bufferSize]; while (!stopper.value()) { int count = line.read(buffer, 0, buffer.length); if (count > 0) { out.write(buffer, 0, count); } } line.close(); } catch (java.lang.Exception e) { throw new AudioUtil.Exception(e); } } private static void _validateAudioFormat(AudioFormat format) throws AudioUtil.Exception { if (format.getSampleSizeInBits() != 16 || format.getChannels() != 1 || format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { throw new AudioUtil.Exception( new UnsupportedAudioFormatException()); } } public static void read(AudioFormat sourceFormat, InputStream sourceStream, OutputStream outStream) throws AudioUtil.Exception { _validateAudioFormat(sourceFormat); try { int read; int bufferSize = (int) sourceFormat.getSampleRate() * sourceFormat.getFrameSize(); byte buffer[] = new byte[bufferSize]; while ((read = sourceStream.read(buffer, 0, buffer.length)) != (-1)) { outStream.write(buffer, 0, read); } } catch (java.lang.Exception e) { throw new AudioUtil.Exception(e); } } }