Reputation: 127
I have a program that will ask the user which songs they want to play out of a list of available songs and after the user selects one once the song finishes it asks the user which song they want to play again. My question is how do I prevent the loop from asking the user which song they want to play until the selected song is finished so they don't repeat?
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] pathnames;
File MusicFileChosen;
String musicDir;
boolean songComplete = false;
pathnames = ProgramMap.musicDir.list();
// Print the names of files and directories
for (int ListNum = 0; ListNum < pathnames.length; ListNum++) {
System.out.println(ListNum + 1 + ". " + pathnames[ListNum]);
}
for (int playlistLength = 0; playlistLength < pathnames.length; playlistLength++){
if (!songComplete) {
System.out.println("Which Song would you like to play?");
int musicChoice = input.nextInt();
musicDir = ProgramMap.userDir + "\\src\\Music\\" + pathnames[musicChoice - 1];
MusicFileChosen = new File(musicDir);
PlaySound(MusicFileChosen, pathnames[musicChoice - 1]);
}
}
}
public static void PlaySound(File sound, String FileName){
try{
// Inits the Audio System
Clip clip = AudioSystem.getClip();
AudioInputStream AudioInput = AudioSystem.getAudioInputStream(sound);
//Finds and accesses the clip
clip.open(AudioInput);
//Starts the clip
clip.start();
System.out.println("Now Playing " + FileName);
clip.drain();
}catch (Exception e){
System.out.println("Error playing music");
}
}
}
Upvotes: 0
Views: 49
Reputation: 7910
You can use a LineListener. Then, register and listen for LineEvent.Type.CLOSE.
By the way, you might do better to use SourceDataLine
than Clip
. Maybe not a big deal, but given what you've coded, there could be audible lag, depending on the size of the file, every time you open a clip and load the complete file into memory (this has to be completed before playing can start). The SourceDataLine
will commence playing almost immediately (only loads one buffer before starting to play) and only consumes the one buffer of memory instead of the entire sound file.
A lot of people that are new to javax.sound.sampled
are wary of using SourceDataLine
but it really isn't that much more difficult to code than a Clip
, and for the use you are showing, it would be a better fit.
Upvotes: 1