Play the specified audio input stream serially. - Java javax.sound.sampled

Java examples for javax.sound.sampled:Audio

Description

Play the specified audio input stream serially.

Demo Code

/*/*from  ww w.j  a  v a2 s .c o m*/
 * Copyright (c) 2011, 2020, Frank Jiang and/or its affiliates. All rights
 * reserved.
 * AudioUtils.java is built in 2013-2-14.
 */
//package com.java2s;
import java.io.File;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class Main {
    /**
     * Play the specified audio input stream serially.
     * 
     * @param ais
     *            The specified audio input stream.
     */
    public static void play(AudioInputStream ais) {
        try {
            AudioFormat format = ais.getFormat();
            int bufferSize = format.getFrameSize()
                    * Math.round(format.getFrameRate() / 10);
            byte[] buffer = new byte[bufferSize];
            SourceDataLine line;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                    format);
            line = (SourceDataLine) AudioSystem.getLine(info);
            line.open(format, bufferSize);
            // start the line
            line.start();
            // copy data to the line
            int numBytesRead = 0;
            while (numBytesRead != -1) {
                numBytesRead = ais.read(buffer, 0, buffer.length);
                if (numBytesRead != -1)
                    line.write(buffer, 0, numBytesRead);
            }
            // wait until all data is played, then close the line
            line.drain();
            line.close();
        } catch (Throwable t) {
        }
    }

    /**
     * Play the specified audio file serially.
     * 
     * @param audioFile
     *            The file of specified audio.
     */
    public static void play(File audioFile) {
        try {
            play(AudioSystem.getAudioInputStream(audioFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials