Reputation: 57
I have been trying to animate a character using Java Swing Graphics. I transition from the main screen to a JPanel that is supposed to display an animation simultaneously while audio (WAV file) runs. However, the audio runs first, and then the JPanel is shown & animated instead.
How can I fix this error in my code so that both audio and animation function simultaneously?
I know there is an error with my Thread.sleep() function that forces the entire thread to sleep. But, I cannot figure out how to run my audio without the Thread.sleep(), and the threads will not run simultaneously with the Thread.sleep() method present.
I am currently using Java 8.
Audio Class
import java.io.*;
import javax.sound.sampled.*;
public class AudioManager
{
static AudioInputStream audioInputStream = null;
static Clip curClip = null;
public static void playSound(String fileName)
{
System.out.println("Playing Sound");
new Thread(new Runnable()
{
public void run()
{
try
{
audioInputStream = AudioSystem.getAudioInputStream(new File(fileName));
curClip = AudioSystem.getClip();
curClip.open(audioInputStream); //Opens Stream
curClip.start();
Thread.sleep(curClip.getMicrosecondLength() / 1000); //Pauses the thread
audioInputStream.close();
curClip.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}).run();
}
}
Animator Class calling the Audio Method
Timer t1 = new Timer(background_Intro_Speed, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println(isShowing());
if(isShowing())
{
System.out.println(audioOver);
if(audioOver && animated.xPosition <= 905)
animated.xPosition += 5;
else if(animated.xPosition > 905 && audioOver)
{
System.out.println("Animation Ended");
swapPanel();
}
else if(!audioOver)
{
new Thread(new Runnable()
{
public void run()
{
System.out.println("In Thread");
AudioManager.playSound("foo.wav");
audioOver = true;
}
}).run();
}
}
}
});
t1.start();
Upvotes: 0
Views: 74
Reputation: 324187
}).run();
Your Thread is not a Thread. You are just executing the run() method of the Thread.
The code should be:
}).start();
to start a separate Thread so the code doesn't execute on the Event Dispatch Thread.
Upvotes: 1