问题
I'm successfully playing sounds in a Java (1.5) applet game using the following code:
// get an available clip to play it
Clip clip = null;
for (Clip clipTemp : players) {
if (!clipTemp.isOpen()) {
clip = clipTemp;
break;
}
}
if (clip == null) {
// no available player found, don't play
return;
}
clip.open(audioFormat, audioByteData, 0, audioByteData.length);
clip.start();
(Players are a list of clips that I open at the start with the aim to reduce latency, a line listener closes the line when the stop event is retrieved.)
The problem I'm facing is intermittent delays of upto 1 second when playing a sound. This is pretty poor.
Is there any way to improve this? Are SourceDataLines
worth considering?
回答1:
The Java Applet is streaming your clip whenever you want to play it, which is why you are getting a delay as the sound file hasn't been loaded into memory yet.
It's been awhile since I have done Java applet programming, but I do remember that I used to pre-load all my clips and then subsequent calls to play would not re-open the files.
Here is some code from one of my old projects
Clip shoot;
private loadShootWav()
{
AudioInputStream sample;
sample = AudioSystem.getAudioInputStream(this.getClass().getResource("shoot.wav"));
shoot = AudioSystem.getClip();
shoot.open(sample);
}
public void playShootSFX()
{
shoot.stop();
shoot.setFramePosition(0);
shoot.start();
}
回答2:
If I am reading your code correctly, you are finding an unopened clip and opening it before playing it. It would be quicker to take opened clips and restart them. You might have to stop and reset their positions first, as shown by JSmyth in playShootSFX() example.
I am getting pretty good response with SourceDataLines. The nice thing is that they start quicker than an unopened Clip, since they start right away instead of waiting until ALL the data for the sound is loaded into RAM (which occurs each time you "open" a Clip).
But, yes, if you have a lot of little sounds that are played frequently, a clip pool is the way to go. If you want them to overlap, or always play to completion, then you need multiple copies. If not, then stop, reset to 0 and restart. But don't keep reopening! If you are doing that, you might as well use a SourceDataLine.
来源:https://stackoverflow.com/questions/2246809/how-to-play-sounds-in-java-games