read by audio format - Java javax.sound.sampled

Java examples for javax.sound.sampled:Audio

Description

read by audio format

Demo Code


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 read(AudioFormat sourceFormat,
            InputStream sourceStream, OutputStream outStream)
            throws AudioUtil.Exception {
        _validateAudioFormat(sourceFormat);
        try {/*w  ww  .  j  a v a 2s  .c  o  m*/
            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);
        }
    }
    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());
        }
    }
}

Related Tutorials