Sino
Sino

Reputation: 990

Perform action after end of the sound

I am able to play sounds in my Java Swing application right now usind JavaSound and code from Java play WAV sound file. What I currently want to do is:

Play a sound; after the sound is finished I want to play another sound (which is the action). So basically, in steps:

  1. Play a sound. (I know how long this sound takes - 4 seconds).
  2. After end of sound.
  3. Perform action (e.g. play another sound).

I tried several options, delays, threads but couldn’t figure it out.

Upvotes: 1

Views: 1855

Answers (2)

Alberto Solano
Alberto Solano

Reputation: 8227

As an alternative to the good solution of Abbas, I can suggest to periodically check if the thread you use to play the file is alive.

Looking the tutorial provided by you, the main program creates a new instance of the thread class and uses the start() method to start the thread. So, you can check if the thread is still alive. When the thread is dead you can do what you want. For example:

    AePlayWave apw = new AePlayWave("test.wav");
    apw.start();

    try{
        boolean alive = apw.isAlive();
        while(alive){
            //check periodically if the thread is alive         
            alive = apw.isAlive();
            Thread.currentThread().sleep(500);

            }

    }

    catch(InterruptedException e){
        System.out.println("Interrupted");
        e.printStackTrace();
    }

//do other action..

When the apw thread is dead (then boolean alive is false) and the program is quitting from the while loop, you can perform what you want.

Upvotes: 2

Abbas
Abbas

Reputation: 6886

In your example, a DataLine object is being used to play a sound. The DataLine object has a method call addLineListener which takes an object that implements the LineListener interface and exposes events such as start and stop that you can use to perform your action or play another sound.

What you need to do is:

  1. Implement the LineListener interface in your class
  2. Subscribe to an update event by calling the addLineListener method with this argument
  3. Implement the update method of the LineListener interface
  4. Test the event in update method and provide the action you require

Here's a link that demonstrates processing LineListener events in the update method.

Upvotes: 4

Related Questions