Example usage for javax.sound.sampled AudioInputStream close

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this audio input stream and releases any system resources associated with the stream.

Usage

From source file:SoundPlayer.java

public SoundPlayer(File f, boolean isMidi) throws IOException, UnsupportedAudioFileException,
        LineUnavailableException, MidiUnavailableException, InvalidMidiDataException {
    if (isMidi) { // The file is a MIDI file
        midi = true;/*from ww  w .j a  v a 2 s  .c  o  m*/
        // First, get a Sequencer to play sequences of MIDI events
        // That is, to send events to a Synthesizer at the right time.
        sequencer = MidiSystem.getSequencer(); // Used to play sequences
        sequencer.open(); // Turn it on.

        // Get a Synthesizer for the Sequencer to send notes to
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open(); // acquire whatever resources it needs

        // The Sequencer obtained above may be connected to a Synthesizer
        // by default, or it may not. Therefore, we explicitly connect it.
        Transmitter transmitter = sequencer.getTransmitter();
        Receiver receiver = synth.getReceiver();
        transmitter.setReceiver(receiver);

        // Read the sequence from the file and tell the sequencer about it
        sequence = MidiSystem.getSequence(f);
        sequencer.setSequence(sequence);
        audioLength = (int) sequence.getTickLength(); // Get sequence length
    } else { // The file is sampled audio
        midi = false;
        // Getting a Clip object for a file of sampled audio data is kind
        // of cumbersome. The following lines do what we need.
        AudioInputStream ain = AudioSystem.getAudioInputStream(f);
        try {
            DataLine.Info info = new DataLine.Info(Clip.class, ain.getFormat());
            clip = (Clip) AudioSystem.getLine(info);
            clip.open(ain);
        } finally { // We're done with the input stream.
            ain.close();
        }
        // Get the clip length in microseconds and convert to milliseconds
        audioLength = (int) (clip.getMicrosecondLength() / 1000);
    }

    // Now create the basic GUI
    play = new JButton("Play"); // Play/stop button
    progress = new JSlider(0, audioLength, 0); // Shows position in sound
    time = new JLabel("0"); // Shows position as a #

    // When clicked, start or stop playing the sound
    play.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (playing)
                stop();
            else
                play();
        }
    });

    // Whenever the slider value changes, first update the time label.
    // Next, if we're not already at the new position, skip to it.
    progress.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            int value = progress.getValue();
            // Update the time label
            if (midi)
                time.setText(value + "");
            else
                time.setText(value / 1000 + "." + (value % 1000) / 100);
            // If we're not already there, skip there.
            if (value != audioPosition)
                skip(value);
        }
    });

    // This timer calls the tick() method 10 times a second to keep
    // our slider in sync with the music.
    timer = new javax.swing.Timer(100, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tick();
        }
    });

    // put those controls in a row
    Box row = Box.createHorizontalBox();
    row.add(play);
    row.add(progress);
    row.add(time);

    // And add them to this component.
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    this.add(row);

    // Now add additional controls based on the type of the sound
    if (midi)
        addMidiControls();
    else
        addSampledControls();
}

From source file:sec_algo.aud_sec.java

public BufferedWriter getAudioStream() {
    FileInputStream fin = null;/*from w ww  .  j  a va 2  s  . c o  m*/
    BufferedWriter audstream = null;

    try {
        fin = new FileInputStream(this.file);
        //           audstream = new BufferedWriter(new FileWriter(returnFileName()+"_ex."+returnFileExt()));
        //           byte contents[] = new byte[100];
        //           while(fin.read(contents)!= -1){
        //               System.out.println("reading & writing from file");
        //               for(byte b : contents)
        //                   for(int x = 0; x < 8; x++)
        //                       audstream.write(b>>x & 1);
        //           }
        //           System.out.println("Finished!");
        //           System.out.println("audstream contents: " + audstream.toString());
        byte[] header = new byte[8];
        fin.read(header);
        fin.close();
        //           System.out.println("header bytes: " + Arrays.toString(header));
        ArrayList<String> bitstring = new ArrayList<String>();
        for (int i = 0; i < header.length; i++)
            bitstring.add(String.format("%8s", Integer.toBinaryString(header[i] & 0xFF)).replace(' ', '0'));
        System.out.print("bit input: [/");
        for (int i = 0; i < bitstring.size(); i++) {
            System.out.print(bitstring.get(i) + " ");
        }
        System.out.println("]/");

        System.out.println(bitstring.get(0) + " " + bitstring.get(1) + " " + bitstring.get(2));
        System.out.println("Bitrate index: " + bitstring.get(2).substring(0, 4));

        AudioInputStream in = AudioSystem.getAudioInputStream(this.file);
        AudioInputStream din = null;
        AudioFormat baseFormat = in.getFormat();
        AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(),
                getBitrate(bitstring.get(2).substring(0, 4)), baseFormat.getChannels(),
                baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
        din = AudioSystem.getAudioInputStream(decodedFormat, in);
        int size = din.available();
        byte[] bytaud = new byte[size];
        din.read(bytaud);
        bitstring = new ArrayList<String>();
        for (int i = 0; i < header.length; i++)
            bitstring.add(String.format("%8s", Integer.toBinaryString(header[i] & 0xFF)).replace(' ', '0'));
        System.out.print("bit input: [/");
        for (int i = 0; i < bitstring.size(); i++) {
            System.out.print(bitstring.get(i) + " ");
        }
        System.out.println("]/");
        in.close();
        din.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return audstream;
}

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

/**
 * Plays a sound.//from   ww w  .j a  v a  2s .  c  om
 *
 * @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;
}

From source file:it.sardegnaricerche.voiceid.sr.VCluster.java

public void trimSegments(File inputFile) throws IOException {
    String base = Utils.getBasename(inputFile);
    File mydir = new File(base);
    mydir.mkdirs();/*from  w ww.  j a va 2 s. c  om*/
    String mywav = mydir.getAbsolutePath() + "/" + this.getLabel() + ".wav";
    AudioFileFormat fileFormat = null;
    AudioInputStream inputStream = null;
    AudioInputStream shortenedStream = null;
    AudioInputStream current = null;
    int bytesPerSecond = 0;
    long framesOfAudioToCopy = 0;
    wavFile = new File(mywav);
    try {
        fileFormat = AudioSystem.getAudioFileFormat(inputFile);
        AudioFormat format = fileFormat.getFormat();
        boolean firstTime = true;

        for (VSegment s : this.getSegments()) {
            bytesPerSecond = format.getFrameSize() * (int) format.getFrameRate();
            inputStream = AudioSystem.getAudioInputStream(inputFile);
            inputStream.skip(0);
            inputStream.skip((int) (s.getStart() * 100) * bytesPerSecond / 100);
            framesOfAudioToCopy = (int) (s.getDuration() * 100) * (int) format.getFrameRate() / 100;

            if (firstTime) {
                shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
            } else {
                current = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
                shortenedStream = new AudioInputStream(new SequenceInputStream(shortenedStream, current),
                        format, shortenedStream.getFrameLength() + framesOfAudioToCopy);
            }
            firstTime = false;
        }
        AudioSystem.write(shortenedStream, fileFormat.getType(), wavFile);
    } catch (Exception e) {
        logger.severe(e.getMessage());
        e.printStackTrace();
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
        if (shortenedStream != null)
            try {
                shortenedStream.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
        if (current != null)
            try {
                current.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
    }
    logger.fine("filename: " + wavFile.getAbsolutePath());
}

From source file:gui.EventReader.java

@Override
public void run() {

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    //HttpClient client = new DefaultHttpClient();

    HttpGet request = new HttpGet(
            //"https://api.guildwars2.com/v1/events.json?world_id="
            "http://gw2eventer.sourceforge.net/api/events.php?world_id=" + this.worldID);

    HttpResponse response;// w  w w  .j a v a 2  s .  c  o m

    String line = "";
    String out = "";

    while (!isInterrupted()) {

        try {

            this.labelWorking.setText(this.workingString);

            try {

                response = client.execute(request);

                if (response.getStatusLine().toString().contains("200")) {

                    BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")));

                    line = "";
                    out = "";

                    while ((line = rd.readLine()) != null) {

                        out = out + line;
                    }
                } else {
                    // http error
                    request.releaseConnection();

                    this.refreshSelector.setEnabled(false);
                    this.workingButton.setEnabled(false);
                    this.jComboBoxLanguage.setEnabled(false);
                    this.labelWorking.setText("connection error. retrying in... 10.");
                    this.labelWorking.setVisible(true);

                    Thread.sleep(10000);
                    continue;
                }
            } catch (IOException | IllegalStateException ex) {

                Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex);

                request.releaseConnection();

                this.refreshSelector.setEnabled(false);
                this.workingButton.setEnabled(false);
                this.jComboBoxLanguage.setEnabled(false);
                this.labelWorking.setText("connection error. retrying in... 10.");
                this.labelWorking.setVisible(true);

                Thread.sleep(10000);
                continue;
                //this.interrupt();
            }

            request.releaseConnection();

            JSONParser parser = new JSONParser();

            Object obj;

            this.result.clear();

            HashMap mehrfachEvents = new HashMap();
            playSoundsList.clear();

            this.overlayGui.clearActive();
            String toolTip;

            try {

                obj = parser.parse(out);

                for (int i = 0; i < this.eventLabels.size(); i++) {

                    JLabel iter = (JLabel) this.eventLabels.get(i);
                    iter.setEnabled(false);
                    iter.setForeground(Color.green);
                }

                for (Iterator iterator = ((JSONObject) obj).values().iterator(); iterator.hasNext();) {

                    JSONArray arrayNew = (JSONArray) iterator.next();

                    for (int i = 0; i < arrayNew.size(); i++) {

                        JSONObject obj2 = (JSONObject) arrayNew.get(i);

                        if (obj2.get("event_id") != null) {

                            String event = (String) obj2.get("event_id");

                            if (this.events.containsKey(event)) {

                                //System.out.println("debug: " + event + "\n");
                                this.result.add(obj2.get("event_id"));

                                int indexEvent = Integer.parseInt(((String[]) this.events.get(event))[0]);
                                String eventPercent = ((String[]) this.events.get(event))[1];
                                String eventWav = ((String[]) this.events.get(event))[2];
                                String eventName = ((String[]) this.events.get(event))[3];

                                JLabel activeLabel = (JLabel) this.eventLabels.get(indexEvent - 1);
                                JLabel activeLabelTimer = (JLabel) this.eventLabelsTimer.get(indexEvent - 1);

                                int activeLabelInt = indexEvent - 1;
                                String tmpEventName = eventPercent.substring(0, 1);

                                Date dateNow = new Date();
                                long stampNow = dateNow.getTime();

                                if (this.timerStamps[activeLabelInt] != null) {

                                    long oldTimestamp = this.timerStamps[activeLabelInt].getTime();
                                    long minsdiff = ((stampNow - oldTimestamp) / 1000 / 60);

                                    if (minsdiff >= 30) {
                                        activeLabelTimer.setEnabled(true);
                                    } else {
                                        activeLabelTimer.setEnabled(false);
                                    }

                                    if (minsdiff >= 60) {
                                        activeLabelTimer.setForeground(Color.red);
                                    } else {
                                        activeLabelTimer.setForeground(Color.green);
                                    }

                                    activeLabelTimer.setText(minsdiff + " mins (B)");
                                }

                                /*
                                if (activeLabel != null) {
                                if (activeLabel.getToolTipText() != null) {
                                    if (activeLabel.getToolTipText().equals("")) { // null pointer??
                                        activeLabel.setToolTipText((String) this.allEvents.get(obj2.get("event_id")));
                                    }
                                }
                                }*/

                                if (obj2.get("state").equals("Active")) {

                                    activeLabel.setEnabled(true);

                                    //activeLabel.setToolTipText((String) this.allEvents.get(obj2.get("event_id")));

                                    toolTip = activeLabel.getToolTipText();

                                    if (toolTip != null) {

                                        if (toolTip.length() > 35) {
                                            toolTip = toolTip.substring(0, 35) + "...";
                                        }
                                    } else {
                                        toolTip = "";
                                    }

                                    if (tmpEventName.equals("B")) {

                                        this.markedBs[activeLabelInt] = true;
                                        activeLabelTimer.setVisible(false);
                                        this.timerStamps[activeLabelInt] = null;

                                        if (this.eventPlaySounds[activeLabelInt][2]) {
                                            if (!this.overlayGui.containsActiveB(eventName)) {
                                                this.overlayGui.addActiveB(eventName, "yellow", activeLabelInt);
                                            }
                                        } else {
                                            if (!this.overlayGui.containsActiveB(eventName)) {
                                                this.overlayGui.addActiveB(eventName, "green", activeLabelInt);
                                            }
                                        }
                                    } else {

                                        if (this.eventPlaySounds[activeLabelInt][2]) {
                                            if (!this.overlayGui.containsActivePre(eventName)) {
                                                this.overlayGui.addActivePreEvent(eventName, "yellow",
                                                        activeLabelInt);
                                            }
                                        } else {
                                            if (!this.overlayGui.containsActivePre(eventName)) {
                                                this.overlayGui.addActivePreEvent(eventName, "green",
                                                        activeLabelInt);
                                            }
                                        }
                                    }

                                    //activeLabel.setSize(100, activeLabel.getSize().height);
                                    //activeLabel.setText(eventPercent);

                                    URL url = this.getClass().getClassLoader()
                                            .getResource("media/sounds/" + eventWav + ".wav");

                                    if (!playSoundsList.containsKey(url)) {

                                        if (!this.eventPlaySounds[activeLabelInt][2]) {
                                            if (tmpEventName.equals("B")) {
                                                if (this.eventPlaySounds[activeLabelInt][1]) {

                                                    playSoundsList.put(url, activeLabel);
                                                }
                                            } else {
                                                if (this.eventPlaySounds[activeLabelInt][0]) {

                                                    playSoundsList.put(url, activeLabel);
                                                }
                                            }
                                        } else {
                                            activeLabel.setForeground(Color.YELLOW);
                                        }
                                    }

                                    if (mehrfachEvents.containsKey(activeLabel)) {
                                        ((ArrayList) mehrfachEvents.get(activeLabel)).add(tmpEventName);
                                    } else {
                                        ArrayList tmpListe = new ArrayList();
                                        tmpListe.add(tmpEventName);
                                        mehrfachEvents.put(activeLabel, tmpListe);
                                    }
                                } else {

                                    if (tmpEventName.equals("B")) {
                                        if (this.markedBs[activeLabelInt]) {

                                            this.timerStamps[activeLabelInt] = dateNow;
                                            this.markedBs[activeLabelInt] = false;

                                            activeLabelTimer.setVisible(true);
                                            activeLabelTimer.setText("0 mins (B)");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                Iterator it = mehrfachEvents.entrySet().iterator();

                while (it.hasNext()) {

                    Map.Entry pairs = (Map.Entry) it.next();

                    JLabel label = (JLabel) pairs.getKey();
                    ArrayList liste = (ArrayList) pairs.getValue();
                    String outString = null;

                    Collections.sort(liste, new Comparator<String>() {
                        public int compare(String f1, String f2) {
                            return -f1.toString().compareTo(f2.toString());
                        }
                    });

                    for (int i = 0; i < liste.size(); i++) {

                        if (outString == null) {
                            outString = (String) liste.get(i);
                        } else {
                            outString += ", " + (String) liste.get(i);
                        }
                    }

                    label.setText(outString);

                    it.remove();
                }

                this.labelServer.setOpaque(true);
                this.labelServer.setOpaque(false);
                this.labelServer.setEnabled(false);
                this.labelServer.setText("");
                this.labelServer.setText(this.worldName);

                this.labelWorking.setVisible(false);
                this.refreshSelector.setEnabled(true);
                this.workingButton.setEnabled(true);
                this.jComboBoxLanguage.setEnabled(true);

                this.overlayGui.renderActive();

                if (playSounds) {

                    this.playThread = new Thread() {

                        @Override
                        public void run() {

                            Iterator it = playSoundsList.entrySet().iterator();

                            while (it.hasNext() && !isInterrupted()) {

                                AudioInputStream audioIn;

                                Map.Entry pairs = (Map.Entry) it.next();

                                JLabel label = (JLabel) pairs.getValue();

                                try {

                                    playSoundsCurrent = (URL) pairs.getKey();
                                    audioIn = AudioSystem.getAudioInputStream(playSoundsCurrent);

                                    Clip clip = null;
                                    String tmp = label.getText();

                                    try {
                                        //label.setText(">" + tmp);
                                        //label.setText("<HTML><U>" + tmp + "<U><HTML>");
                                        label.setForeground(Color.red);

                                        //Font font = label.getFont();
                                        //Map attributes = font.getAttributes();
                                        //attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
                                        //label.setFont(font.deriveFont(attributes));

                                        clip = AudioSystem.getClip();
                                        clip.open(audioIn);

                                        clip.start();
                                    } catch (LineUnavailableException ex) {
                                        Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null,
                                                ex);
                                    } finally {
                                        try {
                                            audioIn.close();
                                        } catch (IOException ex) {
                                            Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE,
                                                    null, ex);
                                        }
                                    }

                                    try {
                                        Thread.sleep(2000);
                                        //label.setText(tmp);
                                        label.setForeground(Color.green);
                                    } catch (InterruptedException ex) {
                                        Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null,
                                                ex);
                                        this.interrupt(); //??
                                    }
                                } catch (UnsupportedAudioFileException ex) {
                                    Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex);
                                } catch (IOException ex) {
                                    Logger.getLogger(EventReader.class.getName()).log(Level.SEVERE, null, ex);
                                }

                                it.remove();
                            }
                        }
                    };

                    this.playThread.start();
                    this.playThread.join();
                }

            } catch (ParseException ex) {

                Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex);

                this.refreshSelector.setEnabled(false);
                this.workingButton.setEnabled(false);
                this.jComboBoxLanguage.setEnabled(false);
                this.labelWorking.setText("connection error. retrying in... 10.");
                this.labelWorking.setVisible(true);

                Thread.sleep(10000);
                continue;
            }

            if (this.autoRefresh) {

                Thread.sleep(this.sleepTime * 1000);
            } else {

                this.interrupt();
            }
        } catch (InterruptedException ex) {

            Logger.getLogger(ApiManager.class.getName()).log(Level.SEVERE, null, ex);

            this.interrupt();
        }
    }
}

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 {//  w  ww . ja  va2  s.c om
        // 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();
    }
}