Im trying to play six audio tracks simultaneously on the click of a jbutton, but upon click it plays the first track and waits until it finishes to play the second track, and so on. Here is my code
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println("Button Pressed");
AudioPlayerExample2 player1 = new AudioPlayerExample2();
AudioPlayerExample2 player2 = new AudioPlayerExample2();
AudioPlayerExample2 player3 = new AudioPlayerExample2();
AudioPlayerExample2 player4 = new AudioPlayerExample2();
AudioPlayerExample2 player5 = new AudioPlayerExample2();
AudioPlayerExample2 player6 = new AudioPlayerExample2();
player1.play(track1);
player2.play(track2);
player3.play(track3);
player4.play(track4);
player5.play(track5);
player6.play(track6);
}
}
});
and the audio player imported
public class AudioPlayerExample2 {
private static final int BUFFER_SIZE = 4096;
public void play(String audioFilePath) {
File audioFile = new File(audioFilePath);
try {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
SourceDataLine audioLine = (SourceDataLine) AudioSystem.getLine(info);
audioLine.open(format);
audioLine.start();
System.out.println("Playback started.");
byte[] bytesBuffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = audioStream.read(bytesBuffer)) != -1) {
audioLine.write(bytesBuffer, 0, bytesRead);
}
audioLine.drain();
audioLine.close();
audioStream.close();
System.out.println("Playback completed.");
} catch (UnsupportedAudioFileException ex) {
System.out.println("The specified audio file is not supported.");
ex.printStackTrace();
} catch (LineUnavailableException ex) {
System.out.println("Audio line for playing back is unavailable.");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Error playing the audio file.");
ex.printStackTrace();
}
}
public static void main(String[] args) {
String audioFilePath = "";
AudioPlayerExample2 player = new AudioPlayerExample2();
player.play(audioFilePath);
}}
While the track is playing, the button also remains clicked, so I am unable to use my volume jslider as well. Thanks for the help!