I have written a simple class to play audio files in a simple game. It works fine for small sounds like a gunshot or explosion, but when I tried to use it for background music I got this error: ‘Failed to allocate clip data: Requested buffer too large.’ I am assuming this means that the file is too large, but how can I get around this?
Source:
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class Sound{
private Clip clip;
public Sound(String filepath){
System.out.println(filepath);
File file = new File(filepath);
try {
clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
clip.open(inputStream);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public void play(){
System.out.println("play");
if(clip.isActive()){
clip.stop();
}
clip.setFramePosition(0);
clip.start();
}
public void stop(){
clip.stop();
}
public void loop(){
if(!clip.isActive()){
clip.setFramePosition(0);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}else{
System.out.println("ALREADY PLAYING");
}
}
public boolean getActive(){return clip.isActive();}
}
Use
BigClip. It is a class I put together to play MP3s of 12-18 minutes (or more1).It requires the
mp3plugin.jaron the run-time class-path to actually load MP3 format sound, but that is not the point. The point is:BigClipwill load sound files to the maximum memory the JVM will allow beforeOutOfMemoryError.