Like all other InputStreams, AudioInputStream can only be read once (unless it can be .reset()). You could try calling .reset() on the AudioInputStream before attemping to play the sound again, but AudioInputStream may not support .reset(). InputStreams are not required to support reset. Also see markSupported().
If .reset() doesn't work, consider constructing a new AudioInputStream every time you need to start playing.
UPDATE: I made an example of caching sound data in memory and using Clip to play those sounds. This example utilizes AudioInputStream.reset(). So how can that work? In fact, AudioInputStream does supports reset() if and only if its underlying InputStream supports .reset(). So my example creates an AudioInputStream that is backed by a ByteArrayInputStream. Because ByteArrayInputStream supports reset, these cached AudioInputStreams also support .reset(), which allows them to be reused.
Note that if you are going to be playing any one cached sound concurrently, you should probably not cache AudioInputStream
s, but rather cache byte[]
s and construct an AudioInputStream
per-playback. This is because AudioInputStream
is stateful, so passing a single instance of it to two concurrently running clips, or resetting a stream while one clip is playing, will result in state conflict.
public class CachedSoundClipTest
{
static ArrayList<AudioInputStream> cachedSounds =
new ArrayList<AudioInputStream>();
public static void main(String[] args) throws Exception
{
File[] audioFiles = new File("/audio_storage_directory").listFiles();
for (File file : audioFiles)
{
AudioInputStream reusableAudioInputStream =
createReusableAudioInputStream(file);
cachedSounds.add(reusableAudioInputStream);
}
while(true)
{
System.out.println("Press enter to play next clip");
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
br.readLine();
playCachedSound(0);
}
}
private static void playCachedSound(int i)
throws IOException, LineUnavailableException
{
AudioInputStream stream = cachedSounds.get(i);
stream.reset();
Clip clip = AudioSystem.getClip();
clip.open(stream);
clip.start();
}
private static AudioInputStream createReusableAudioInputStream(File file)
throws IOException, UnsupportedAudioFileException
{
AudioInputStream ais = null;
try
{
ais = AudioSystem.getAudioInputStream(file);
byte[] buffer = new byte[1024 * 32];
int read = 0;
ByteArrayOutputStream baos =
new ByteArrayOutputStream(buffer.length);
while ((read = ais.read(buffer, 0, buffer.length)) != -1)
{
baos.write(buffer, 0, read);
}
AudioInputStream reusableAis =
new AudioInputStream(
new ByteArrayInputStream(baos.toByteArray()),
ais.getFormat(),
AudioSystem.NOT_SPECIFIED);
return reusableAis;
}
finally
{
if (ais != null)
{
ais.close();
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…