I'm having some issues playing mp3 files using AudioClip with JavaFX.
my code is like this:
// define String path to mp3 file
myFilePath = "path/to/file.mp3";
// Create an AudioClip Object from path
audioToPlay = new AudioClip(Objects.requireNonNull(getClass().getResource(audioToPlay)).toExternalForm());
// play the AudioClip
audioToPlay.play();
The audio files I am playing are all mp3 files and they are all fairly short (< 5 seconds). About 80-90% of the files are playing without any issue but the rest aren't playing at all, or are only playing for a very short time (less than a second so it sounds like a click).
I have no idea why the 10-20% aren't working; they play perfectly fine using my media player and from my browser.
Is the issue because I'm using AudioClip? Should I be using something else to play my short audio files?
Edit: myFilePath is defined as a String and audioToPlay is defined as an AudioClip object.
AudioClip
is appropriate for short files that can be held in memory. This issue might be related to how or when you are calling the play() method. Does this occur when calling the play method via a button click, where the GUI stays open? Some folks don't realize playback is a daemon thread. Act of playback won't prevent a program from closing if the program triggers the sound and then completes and exits before the sound finishes playing. Also FWIW, once loaded into memory, there's no need to keep reloadingAudioClip
over and over.Thought I'd add this: it seems to me that sometimes Java doesn't gracefully handle the first audio call in a session, that there is often a stutter. Due to this, I often play a "silent" sound at the start of a program, in order to get things going. Just mentioning, in case the problem occurs when the program is first getting going. If you use a GUI (with button to make sound) then you can test if an additional call repeats the problem or not, and thus help verify whether it's the sound file or the circumstance.