user3150201
user3150201

Reputation: 1947

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).

Upvotes: 2

Views: 836

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168825

The Java Sound based Clip preloads the data, so it should be fine. From the Java Docs.

The Clip interface represents a special kind of data line whose audio data can be loaded prior to playback, instead of being streamed in real time.

Because the data is pre-loaded and has a known length, you can set a clip to start playing at any position in its audio data. ..

Upvotes: 1

JamoBox
JamoBox

Reputation: 766

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?

Upvotes: 1

Related Questions