Java examples for javax.sound.sampled:Audio
loop Audio Format
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 loop(AudioFormat sourceFormat, ValueAccessor<Boolean> stopper, EventListener listener, byte[] bytes) throws AudioUtil.Exception { _validateAudioFormat(sourceFormat); try {//from w w w .j a va 2s.c o m DataLine.Info info = new DataLine.Info(SourceDataLine.class, sourceFormat); SourceDataLine sourceLine = (SourceDataLine) AudioSystem .getLine(info); sourceLine.open(sourceFormat); sourceLine.start(); int read; int totalRead = 0; int bufferSize = 256; byte buffer[] = new byte[bufferSize]; outerLoop: do { ByteArrayInputStream baos = new ByteArrayInputStream(bytes); totalRead = 0; while ((read = baos.read(buffer, 0, buffer.length)) != (-1)) { totalRead += read; sourceLine.write(buffer, 0, read); if (listener != null) { listener.updatePosition(totalRead / sourceFormat.getFrameSize()); } if (stopper != null && stopper.value()) { if (listener != null) listener.stopped(); break outerLoop; } } } while (true); sourceLine.drain(); sourceLine.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); } } }