I'm trying to play a song in the .wav format in my Java Game, and here's some of the code of the SoundPlayer class:
private static HashMap clips;
private static int gap;
public static void init() {
clips = new HashMap();
gap = 0;
}
public static void load(String s, String n) {
if(clips.get(n) != null) return;
Clip clip;
try {
InputStream in = SoundPlayer.class.getResourceAsStream(s);
InputStream bin = new BufferedInputStream(in);
AudioInputStream ais = AudioSystem.getAudioInputStream(bin);
AudioFormat baseFormat = ais.getFormat();
AudioFormat decodeFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
AudioInputStream dais = AudioSystem.getAudioInputStream(decodeFormat, ais);
clip = AudioSystem.getClip();
clip.open(dais);
clips.put(n, clip);
} catch(Exception e) {
e.printStackTrace();
}
}
When I call the load() method, it crashes on the line clip.open(dais) and I'm given this error:
javax.sound.sampled.LineUnavailableException: Failed to allocate clip data: Requested buffer too large.
This works with short sound effects, so I'm guessing this is because the file is over a minute long. Are there any better ways of doing this?
Thanks!
解决方案
I've had some trouble in the past getting sound to work in Java. Here is a good way to load .wav soundclips.
private Clip clip;
public Sound(String fileName)
{
try
{
File file = new File(fileName);
if (file.exists())
{
AudioInputStream sound = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(sound);
}
else
{
throw new RuntimeException("Sound: file not found: " + fileName);
}
}
catch (UnsupportedAudioFileException e)
{
e.printStackTrace();
throw new RuntimeException("Sound: Unsupported Audio File: " + e);
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("Sound: Input/Output Error: " + e);
}
}
public void play()
{
clip.setFramePosition(0);
clip.start();
}
public void loop()
{
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stop()
{
clip.stop();
}
I find that this works great! You can add more exceptions if you'd like as well, like LineUnavailableException, and MalformedURLException. To create a sound clip you make something as such:
private Sound sound = new Sound("/sounds/sound.wav");
then doing
sound.play();