I am trying to make the background music for a game. For some reason, after the song is played for the first time it won't play again. What am I doing wrong and how can i fix it? I know i can use .loop() but i want it to repeat forever, and .loop() will eventually stop.
public class playSong
extends Thread
{
Clip clip=null;
playSong()
{
start();
}
@Override
public void run()
{
while(true)
{
if(clip==null)
{
playSound("fax.wav");
}
else if(!clip.isRunning())
{playSound("fax.wav");}
}
}
public void playSound(String name)
{
try {
File file=new File(this.getClass().getResource(name).getFile());
AudioInputStream audio = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
}
The best would be to use the looping option already existing in Clip .
clip.loop(Clip.LOOP_CONTINUOUSLY);
Here is already an answer describing that : Audio clip looping . It is supposed to fix your endling loop problem that you describe by keeping the thread running.
UPDATE :
Here is a full working example made of your code, modified.
public class PlaySong extends Thread
{
Clip clip=null;
public PlaySong()
{
start();
}
@Override
public void run()
{
playSound("fax.wav");
for(;;)
{
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
public void playSound(String name)
{
try
{
File file = new File(this.getClass().getResource(name).getFile());
AudioInputStream audio = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.