我正在製作一個2D RPG遊戲,並且我想要獲得背景音樂的工作。我寫了一個可以在單獨的線程上播放音樂的健全類,但我無法弄清楚如何讓它循環播放。我的聲音類別如下:在Java中的單獨線程上循環播放音頻
package tileRPG.gfx;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class Sound implements Runnable
{
private String fileLocation = "res/bgMusic.wav";
public Sound() { }
public void play()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
playSound(fileLocation);
}
private void playSound(String fileName)
{
File soundFile = new File(fileName);
AudioInputStream audioInputStream = null;
try
{
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
}
catch (Exception e)
{
e.printStackTrace();
}
AudioFormat audioFormat = audioInputStream.getFormat();
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try
{
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(audioFormat);
}
catch (LineUnavailableException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
line.start();
int nBytesRead = 0;
byte[] abData = new byte[128000];
while (nBytesRead != -1)
{
try
{
nBytesRead = audioInputStream.read(abData, 0, abData.length);
}
catch (IOException e)
{
e.printStackTrace();
}
if (nBytesRead >= 0)
{
int nBytesWritten = line.write(abData, 0, nBytesRead);
}
}
line.drain();
line.close();
}
}
你想再玩一次嗎?請確認。 – Braj
我想讓它繼續播放,直到節目結束 –
@gnomed,我想修復縮進,因爲它的可讀性不好。是的,如果作者不同意,他可以拒絕或撤消它。 –