Reputation:
I'm making a sound player in Java with JavaFX and I'm trying to make multiple WAV files play in sync. But when I call the method which makes my clip.start() run for each file, they are completely out of sync.
This is the code for the method I'm calling when I press my button (play).
private Clip playSound(ArrayList<File> files) {
for (File file : files) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch (Exception e) {
System.err.print("Sound file open error\n " + e.getMessage());
}
}
return clip;
}
How do I fix this?
Upvotes: 1
Views: 135
Reputation: 7910
I've not used this method myself (I wrote my own mixer, instead), but according to the tutorial Playing Back Audio (see bottom section Synchronizing Playback on Multiple Lines) and documentation on Mixer, there exist Mixers that support the synchronization you describe.
It is possible to specify the Mixer
when creating a Clip
rather than using the default Mixer
as you do in the code you show. The syntax should be straightforward to locate in the API. But as to whether there's a Mixer
that will work for a given OS and PC, I have little experience with this. If the isSynchronizationSupported test doesn't work on the default mixer, I'm guessing you just have to iterate and test all available Mixers and hope for the best. IDK.
As I said, I've side-stepped the problem. I am using a mixer that I wrote which handles adding together the PCM data from the constituent "Clips" (actually, AudioCue
s, which are based on Clip
s). With this library you could create and 'play' the audioCues with the mixer off, and then start them all at once by starting the Mixer. The library allows multiple instances of AudioMixer
to be running independently, at the same time, if you have more than one set of cues you are trying to synchronize.
You are welcome to use the AudioCue library. Or you might just inspect the mixing code and write your own. An important benefit of this approach is that this library is not as susceptible to variations in OS implementation of mixer capabilities. Functionality is handled at the PCM level on a SourceDataLine
, a reliable class.
Upvotes: 0
Reputation:
Add a boolean to check if the song is still playing, and if it is, wait
Upvotes: 1