【发布时间】:2014-06-08 22:15:34
【问题描述】:
我正在制作一个 2d RPG 游戏,我想让背景音乐正常工作。我写了一个声音类,在单独的线程上播放音乐,但我不知道如何让它循环。我的声音类如下:
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();
}
}
【问题讨论】:
-
你想再玩一次吗?请确认。
-
我希望它继续重播,直到程序结束
-
@gnomed,我想修复缩进,因为它的可读性不好。是的,如果作者不同意,他可以拒绝或撤消它。
-
花括号的可读性问题在软件开发中是一个长期存在的争论,我认为这个网站不适合告诉人们使用一种风格而不是另一种风格(是编辑所做的一切)。可读性是一种主观意见,相比之下,我发现原来的花括号定位更具可读性(就像 OP 一样)。
-
好的,@gnomed,我同意这是一个长期存在的争论,如果原因仅仅是这个,我不会修复它。如果代码是这样的,我不会修复它。还有不正确的缩进,代码区域外的大括号(看看原来的),目标是修复它。但如果作者不同意,可以撤消它。没问题。
标签: java multithreading loops audio