Source of AudioApplet3.java


  1: //AudioApplet3.java
  2: //Demonstrates the playing of several sounds via an applet.

  4: import java.awt.*;
  5: import java.awt.event.*;
  6: import java.applet.*;

  8: public class AudioApplet3 extends Applet
  9: implements ActionListener
 10: {
 11:     //Initialize an array with the names of the sounds
 12:     String[] soundNames =
 13:         {"Bark", "Computer", "Crash", "Cuckoo",      "Doorbell",
 14:          "Drip", "Gong",     "Ring",  "Space Music", "Train"};

 16:     //Instantiate an array of buttons
 17:     Button[] button = new Button[soundNames.length];

 19:     AudioClip sound;

 21:     //Override init() method to display an array of buttons
 22:     //with the names of the sounds written on the buttons
 23:     public void init()
 24:     {
 25:         setLayout(null);
 26:         setBackground(Color.black);
 27:         for (int index=0; index != soundNames.length; index++)
 28:         {
 29:             button[index] = new Button(soundNames[index]);
 30:             button[index].setLocation(10, 25*index+5);
 31:             button[index].setSize(100, 25);
 32:             button[index].setBackground(Color.cyan);
 33:             button[index].addActionListener(this);
 34:             add(button[index]);
 35:         }
 36:     }

 38:     //Implement the actionPerformed() method, as usual
 39:     public void actionPerformed(ActionEvent event)
 40:     {
 41:         //Find the name of the button that was pressed
 42:         Object source = event.getActionCommand();
 43:         //Inspect each sound name in the array of sound names
 44:         for (int index=0; index!=soundNames.length; index++)
 45:         {
 46:             if (source.equals(soundNames[index]))
 47:             {
 48:                 //Play the appropriate audio clip if matched
 49:                 String audioFile =
 50:                     "audio/" +
 51:                     source.toString().replaceAll(" ", "").toLowerCase() +
 52:                     ".au";
 53:                 sound = getAudioClip(getCodeBase(), audioFile);
 54:                 sound.play();
 55:                 return;
 56:             }
 57:         }
 58:     }
 59: }