0

I have a group of .wav sounds which are contained in a folder within the package. In the following code It will always play the same .wav sound every time the button is pressed. how to to add the Random function to read from the folder and play a different sound each time the button is pressed.

             public void actionPerformed(ActionEvent e){
                if (e.getSource() ==  Button)
                     play("/nameofthefolder/nameofsound.wav");

                    }    
an_barce
  • 11
  • 2
  • 1
    try to get all the file names on an array then loop using math.random*array.size to choose randomly a path of a song look at this it may help [getting all filesnames on folder](http://stackoverflow.com/questions/5694385/getting-the-filenames-of-all-files-in-a-folder) – Mohammed Housseyn Taleb Dec 28 '14 at 13:55

1 Answers1

1
 List<String> results = new ArrayList<String>();


 File[] files = new File("/path/to/the/directory").listFiles();
 //If this pathname does not denote a directory, then listFiles() returns null. 

 for (File file : files) {
  if (file.isFile()) {
    results.add(file.getName());
  }
 }

public void actionPerformed(ActionEvent e){
   String sound=results.get((int) (Math.random()*result.size()));
   play(sound);
 }

tell me if it work.