Sound in Java: Is it okay to use the same AudioInputStream for several Clips?

Here’s a little program I wrote:

package learningSound;

import java.io.*;
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

public class Main extends JFrame {

    Clip clip1,clip2,clip3;
    AudioInputStream audioIn;

    public Main(){

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Test Sound Clip");
        this.setSize(300, 200);
        this.setVisible(true);

        try{

            URL url1 = this.getClass().getResource("ah.wav");
            audioIn = AudioSystem.getAudioInputStream(url1);
            clip1 = AudioSystem.getClip();
            clip1.open(audioIn);

            URL url2 = this.getClass().getResource("eh.wav");
            audioIn = AudioSystem.getAudioInputStream(url2);
            clip2 = AudioSystem.getClip();
            clip2.open(audioIn);

            URL url3 = this.getClass().getResource("ih.wav");
            audioIn = AudioSystem.getAudioInputStream(url3);
            clip3 = AudioSystem.getClip();
            clip3.open(audioIn);

            clip1.start();
            clip2.start();
            clip3.start();

        }catch(Exception e){e.printStackTrace();}

    }

    public static void main(String[] args) {
        new Main();
    }
}

It works, but I wonder if there’s a problem with using the same AudioInputStream for several clips. Is this a problem for some reason? Is this the correct way to manage things?

Also, a completely different question but a small one: If I have a button that when clicked, plays a Clip. Will the timing of the playing of the clip be 100% accurate? (This is for music-making).

Answer

When you call the static method AudioSystem.getAudioInputStream() you are getting the audio input stream from the given URI, as long as that URI points to an audio. This mean what your doing in your code isn’t actually using the same stream. In other words, what you are doing is correct.

As for the ‘part 2’ of the question I’m not sure what you mean by the timing of the clip? Could you expand on that a little?

Leave a Reply

Your email address will not be published. Required fields are marked *