I'm getting some weird behavior from JavaSound in Java 8 in which I have a Sound class and randomly (every 3-5 instances or so) when being created the thread halts for 0-2s
This is constructor method
public Sound(String fileName) { // specify the sound to play // (assuming the sound can be played by the audio system) // from a wave File try { File file = new File(fileName); if (file.exists()) { AudioInputStream sound = AudioSystem.getAudioInputStream(file); // load the sound into memory (a Clip) clip = AudioSystem.getClip(); clip.open(sound); length = clip.getMicrosecondLength(); System.out.println("length: " + length); } else { throw new RuntimeException("Sound: file not found: " + fileName); } } catch (MalformedURLException e) { e.printStackTrace(); throw new RuntimeException("Sound: Malformed URL: " + e); } 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); } catch (LineUnavailableException e) { e.printStackTrace(); throw new RuntimeException("Sound: Line Unavailable Exception Error: " + e); } } My current thoughts are either it is having issues allocating memory(seeing as there are multiple of these instances in an ArrayList), the file is taking long to open from as the coding isn't ideal or it's having trouble removing the objects.
Here's the ArrayList code just in case
public static void playSound(String file){ sounds.add(new Sound("res/" + file)); Sound sound = sounds.get(sounds.size()-1); sound.setVolume(Screen.music.getVolume()); sound.play(); } I've tried running the above section of code in a new thread and the main thread continues but the sounds don't always play.
Edit: I do have some sort of garbage collection to clear up most of the memory for the Sound objects but I don't think the problem is related to that, however reusing the objects might be a valid idea?
public void checkStatus(){ if(clip.getMicrosecondPosition() >= length){ new Thread(){ public void run(){ clip.stop(); clip.close(); clip.flush(); clip.drain(); Screen.sounds.remove(this); } }.start(); } }