0

I am trying to make a program that plays a random WAV file each time the button is pressed. I have everything set up except for how to make it play a random file. How would I make it play a random file from the selection of the two files I have?

public class joeyMain {

public static void main(String[] args) {
    GUI g = new GUI();
    g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    g.setSize(300,200);
    g.setVisible(true);
}

}

public class GUI extends JFrame{

static void PlaySound(File Sound){
    try{
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(Sound));
        clip.start();

        Thread.sleep(clip.getMicrosecondLength()/1000);
    }catch(Exception e){

    }
}

private JButton r;

public GUI(){
    super("AreaFinder");
    setLayout(new FlowLayout());
    setSize(800, 800);

    r = new JButton("Random Joey Quote");
    r.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent arg0) {
            File Joey1 = new File("video1.WAV");
            File Joey2 = new File("video2.WAV"); 
            PlaySound(Joey1);
        }
        public void mouseEntered(MouseEvent arg0) {}
        public void mouseExited(MouseEvent arg0) {}
        public void mousePressed(MouseEvent arg0) {}
        public void mouseReleased(MouseEvent arg0) {}
    });
    add(r);
}

}

3 Answers3

0

You can put them in array and then randomly select one of them.

File[] arr = new File[] {new File("video1.WAV"), new File("video2.WAV")};
Random random = new Random();
PlaySound(arr[random.nextInt(arr.length)]);
Pavan Andhukuri
  • 1,547
  • 3
  • 23
  • 49
0

Create an ArrayList with all the files added to it. Once done you can use the following code mentioned by Fast Snail to generate a random number

ThreadLocalRandom.current().nextInt(min, max + 1);

and get the random file from the array list.

Pavan Andhukuri
  • 1,547
  • 3
  • 23
  • 49
0

Use the Math.random() function:

public void mouseClicked(MouseEvent arg0) {
File Joey1 = new File("video1.WAV");
File Joey2 = new File("video2.WAV");
int rnd2 = (int) (2 * Math.random());
if (rnd2==0) PlaySound(Joey1);
else PlaySound(Joey2);
}
Dior DNA
  • 433
  • 3
  • 11