Example usage for javax.sound.sampled AudioInputStream read

List of usage examples for javax.sound.sampled AudioInputStream read

Introduction

In this page you can find the example usage for javax.sound.sampled AudioInputStream read.

Prototype

@Override
public int read(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads up to a specified maximum number of bytes of data from the audio stream, putting them into the given byte array.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    float sampleRate = 8000;
    int sampleSizeInBits = 8;
    int channels = 1;
    boolean signed = true;
    boolean bigEndian = true;
    final AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);/*from   w ww.  j  a  v  a 2s .  c o m*/
    line.start();
    Runnable runner = new Runnable() {
        int bufferSize = (int) format.getSampleRate() * format.getFrameSize();

        byte buffer[] = new byte[bufferSize];

        public void run() {
            try {

                int count = line.read(buffer, 0, buffer.length);
                if (count > 0) {
                    out.write(buffer, 0, count);
                }

                out.close();
            } catch (IOException e) {
                System.err.println("I/O problems: " + e);
                System.exit(-1);
            }
        }
    };
    Thread captureThread = new Thread(runner);
    captureThread.start();

    byte audio[] = out.toByteArray();
    InputStream input = new ByteArrayInputStream(audio);
    final SourceDataLine line1 = (SourceDataLine) AudioSystem.getLine(info);
    final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
    line1.open(format);
    line1.start();

    runner = new Runnable() {
        int bufferSize = (int) format.getSampleRate() * format.getFrameSize();

        byte buffer[] = new byte[bufferSize];

        public void run() {
            try {
                int count;
                while ((count = ais.read(buffer, 0, buffer.length)) != -1) {
                    if (count > 0) {
                        line1.write(buffer, 0, count);
                    }
                }
                line1.drain();
                line1.close();
            } catch (IOException e) {
                System.err.println("I/O problems: " + e);
                System.exit(-3);
            }
        }
    };
    Thread playThread = new Thread(runner);
    playThread.start();

}

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);
    }/*  w  ww . j ava  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();
}

From source file:Main.java

/** Read sampled audio data from the specified URL and play it */
public static void streamSampledAudio(URL url)
        throws IOException, UnsupportedAudioFileException, LineUnavailableException {
    AudioInputStream ain = null; // We read audio data from here
    SourceDataLine line = null; // And write it here.

    try {/*ww w . j a  v  a2 s.c  o m*/
        // Get an audio input stream from the URL
        ain = AudioSystem.getAudioInputStream(url);

        // Get information about the format of the stream
        AudioFormat format = ain.getFormat();
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

        // If the format is not supported directly (i.e. if it is not PCM
        // encoded, then try to transcode it to PCM.
        if (!AudioSystem.isLineSupported(info)) {
            // This is the PCM format we want to transcode to.
            // The parameters here are audio format details that you
            // shouldn't need to understand for casual use.
            AudioFormat pcm = new AudioFormat(format.getSampleRate(), 16, format.getChannels(), true, false);

            // Get a wrapper stream around the input stream that does the
            // transcoding for us.
            ain = AudioSystem.getAudioInputStream(pcm, ain);

            // Update the format and info variables for the transcoded data
            format = ain.getFormat();
            info = new DataLine.Info(SourceDataLine.class, format);
        }

        // Open the line through which we'll play the streaming audio.
        line = (SourceDataLine) AudioSystem.getLine(info);
        line.open(format);

        // Allocate a buffer for reading from the input stream and writing
        // to the line. Make it large enough to hold 4k audio frames.
        // Note that the SourceDataLine also has its own internal buffer.
        int framesize = format.getFrameSize();
        byte[] buffer = new byte[4 * 1024 * framesize]; // the buffer
        int numbytes = 0; // how many bytes

        // We haven't started the line yet.
        boolean started = false;

        for (;;) { // We'll exit the loop when we reach the end of stream
            // First, read some bytes from the input stream.
            int bytesread = ain.read(buffer, numbytes, buffer.length - numbytes);
            // If there were no more bytes to read, we're done.
            if (bytesread == -1)
                break;
            numbytes += bytesread;

            // Now that we've got some audio data, to write to the line,
            // start the line, so it will play that data as we write it.
            if (!started) {
                line.start();
                started = true;
            }

            // We must write bytes to the line in an integer multiple of
            // the framesize. So figure out how many bytes we'll write.
            int bytestowrite = (numbytes / framesize) * framesize;

            // Now write the bytes. The line will buffer them and play
            // them. This call will block until all bytes are written.
            line.write(buffer, 0, bytestowrite);

            // If we didn't have an integer multiple of the frame size,
            // then copy the remaining bytes to the start of the buffer.
            int remaining = numbytes - bytestowrite;
            if (remaining > 0)
                System.arraycopy(buffer, bytestowrite, buffer, 0, remaining);
            numbytes = remaining;
        }

        // Now block until all buffered sound finishes playing.
        line.drain();
    } finally { // Always relinquish the resources we use
        if (line != null)
            line.close();
        if (ain != null)
            ain.close();
    }
}

From source file:com.skratchdot.electribe.model.esx.impl.SampleImpl.java

/**
 * @param file//from   w ww  .  ja  v  a  2  s .c om
 * @throws EsxException
 */
protected SampleImpl(File file) throws EsxException {
    super();
    init();

    // Declare our streams and formats
    AudioFormat audioFormatEncoded;
    AudioFormat audioFormatDecoded;
    AudioInputStream audioInputStreamEncoded;
    AudioInputStream audioInputStreamDecoded;

    try {
        // Initialize our streams and formats
        audioInputStreamEncoded = AudioSystem.getAudioInputStream(file);
        audioFormatEncoded = audioInputStreamEncoded.getFormat();
        audioFormatDecoded = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                audioFormatEncoded.getSampleRate(), 16, audioFormatEncoded.getChannels(),
                audioFormatEncoded.getChannels() * 2, audioFormatEncoded.getSampleRate(), true);
        audioInputStreamDecoded = AudioSystem.getAudioInputStream(audioFormatDecoded, audioInputStreamEncoded);

        // We have a decoded stereo audio stream
        // Now we need to get the stream info into a list we can manipulate
        byte[] audioData = new byte[4096];
        int nBytesRead = 0;
        long nTotalBytesRead = 0;
        List<Byte> audioDataListChannel1 = new ArrayList<Byte>();
        List<Byte> audioDataListChannel2 = new ArrayList<Byte>();
        boolean isAudioDataStereo = false;

        // Set isAudioDataStereo
        if (audioFormatEncoded.getChannels() == 1) {
            isAudioDataStereo = false;
        } else if (audioFormatEncoded.getChannels() == 2) {
            isAudioDataStereo = true;
        } else {
            throw new EsxException("Sample has too many channels: " + file.getAbsolutePath());
        }

        // Convert stream to list. This needs to be optimized. Converting
        // a byte at a time is probably too slow...
        while (nBytesRead >= 0) {
            nBytesRead = audioInputStreamDecoded.read(audioData, 0, audioData.length);

            // If we aren't at the end of the stream
            if (nBytesRead > 0) {
                for (int i = 0; i < nBytesRead; i++) {
                    // MONO
                    if (!isAudioDataStereo) {
                        audioDataListChannel1.add(audioData[i]);
                        audioDataListChannel2.add(audioData[i]);
                    }
                    // STEREO (LEFT)
                    else if (nTotalBytesRead % 4 < 2) {
                        audioDataListChannel1.add(audioData[i]);
                    }
                    // STEREO (RIGHT)
                    else {
                        audioDataListChannel2.add(audioData[i]);
                    }

                    // Update the total amount of bytes we've read
                    nTotalBytesRead++;
                }
            }

            // Throw Exception if sample is too big
            if (nTotalBytesRead > EsxUtil.MAX_SAMPLE_MEM_IN_BYTES) {
                throw new EsxException("Sample is too big: " + file.getAbsolutePath());
            }
        }

        // Set member variables
        int frameLength = audioDataListChannel1.size() / 2;
        this.setNumberOfSampleFrames(frameLength);
        this.setEnd(frameLength - 1);
        this.setLoopStart(frameLength - 1);
        this.setSampleRate((int) audioFormatEncoded.getSampleRate());
        this.setAudioDataChannel1(EsxUtil.listToByteArray(audioDataListChannel1));
        this.setAudioDataChannel2(EsxUtil.listToByteArray(audioDataListChannel2));
        this.setStereoOriginal(isAudioDataStereo);

        // Set calculated Sample Tune (from Sample Rate)
        SampleTune newSampleTune = EsxFactory.eINSTANCE.createSampleTune();
        float newFloat = newSampleTune.calculateSampleTuneFromSampleRate(this.getSampleRate());
        newSampleTune.setValue(newFloat);
        this.setSampleTune(newSampleTune);

        // Set name
        String newSampleName = new String();
        newSampleName = StringUtils.left(StringUtils.trim(file.getName()), 8);
        this.setName(newSampleName);

        // Attempt to set loopStart and End from .wav smpl chunk
        if (file.getAbsolutePath().toLowerCase().endsWith(".wav")) {
            try {
                RIFFWave riffWave = WavFactory.eINSTANCE.createRIFFWave(file);
                ChunkSampler chunkSampler = (ChunkSampler) riffWave
                        .getFirstChunkByEClass(WavPackage.Literals.CHUNK_SAMPLER);
                if (chunkSampler != null && chunkSampler.getSampleLoops().size() > 0) {
                    SampleLoop sampleLoop = chunkSampler.getSampleLoops().get(0);
                    Long tempLoopStart = sampleLoop.getStart();
                    Long tempLoopEnd = sampleLoop.getEnd();
                    if (tempLoopStart < this.getEnd() && tempLoopStart >= 0) {
                        this.setLoopStart(tempLoopStart.intValue());
                    }
                    if (tempLoopEnd < this.getEnd() && tempLoopEnd > this.getLoopStart()) {
                        this.setEnd(tempLoopEnd.intValue());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
        throw new EsxException("Invalid audio file: " + file.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
        throw new EsxException("Invalid audio file: " + file.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        throw new EsxException("Invalid audio file: " + file.getAbsolutePath());
    }
}

From source file:org.snitko.app.playback.PlaySound.java

private void stream(AudioInputStream in, SourceDataLine sourceDataLine) throws IOException {
    final byte[] buffer = new byte[4096];
    for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
        sourceDataLine.write(buffer, 0, n);
    }//ww w . ja  va 2s  .  c  om
}

From source file:tvbrowser.extras.reminderplugin.ReminderPlugin.java

/**
 * Plays a sound./*  www  .  jav  a 2  s  .c  o  m*/
 *
 * @param fileName
 *          The file name of the sound to play.
 * @return The sound Object.
 */
public static Object playSound(final String fileName) {
    try {
        if (StringUtils.endsWithIgnoreCase(fileName, ".mid")) {
            final Sequencer sequencer = MidiSystem.getSequencer();
            sequencer.open();

            final InputStream midiFile = new FileInputStream(fileName);
            sequencer.setSequence(MidiSystem.getSequence(midiFile));

            sequencer.start();

            new Thread("Reminder MIDI sequencer") {
                @Override
                public void run() {
                    setPriority(Thread.MIN_PRIORITY);
                    while (sequencer.isRunning()) {
                        try {
                            Thread.sleep(100);
                        } catch (Exception ee) {
                            // ignore
                        }
                    }

                    try {
                        sequencer.close();
                        midiFile.close();
                    } catch (Exception ee) {
                        // ignore
                    }
                }
            }.start();

            return sequencer;
        } else {
            final AudioInputStream ais = AudioSystem.getAudioInputStream(new File(fileName));

            final AudioFormat format = ais.getFormat();
            final DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

            if (AudioSystem.isLineSupported(info)) {
                final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

                line.open(format);
                line.start();

                new Thread("Reminder audio playing") {
                    private boolean stopped;

                    @Override
                    public void run() {
                        byte[] myData = new byte[1024 * format.getFrameSize()];
                        int numBytesToRead = myData.length;
                        int numBytesRead = 0;
                        int total = 0;
                        int totalToRead = (int) (format.getFrameSize() * ais.getFrameLength());
                        stopped = false;

                        line.addLineListener(new LineListener() {
                            public void update(LineEvent event) {
                                if (line != null && !line.isRunning()) {
                                    stopped = true;
                                    line.close();
                                    try {
                                        ais.close();
                                    } catch (Exception ee) {
                                        // ignore
                                    }
                                }
                            }
                        });

                        try {
                            while (total < totalToRead && !stopped) {
                                numBytesRead = ais.read(myData, 0, numBytesToRead);

                                if (numBytesRead == -1) {
                                    break;
                                }

                                total += numBytesRead;
                                line.write(myData, 0, numBytesRead);
                            }
                        } catch (Exception e) {
                        }

                        line.drain();
                        line.stop();
                    }
                }.start();

                return line;
            } else {
                URL url = new File(fileName).toURI().toURL();
                AudioClip clip = Applet.newAudioClip(url);
                clip.play();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        if ((new File(fileName)).isFile()) {
            URL url;
            try {
                url = new File(fileName).toURI().toURL();
                AudioClip clip = Applet.newAudioClip(url);
                clip.play();
            } catch (MalformedURLException e1) {
            }
        } else {
            String msg = mLocalizer.msg("error.1", "Error loading reminder sound file!\n({0})", fileName);
            JOptionPane.showMessageDialog(UiUtilities.getBestDialogParent(MainFrame.getInstance()), msg,
                    Localizer.getLocalization(Localizer.I18N_ERROR), JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}