20 likes | 163 Views
Sound/Music. Just as Java has a facility for displaying an image using the ImageIcon class, you can also play sounds/music this facility is only available through the Applet class
E N D
Sound/Music • Just as Java has a facility for displaying an image using the ImageIcon class, you can also play sounds/music • this facility is only available through the Applet class • even though we aren’t going to create applets, we can use this class to generate music in our Jframe/JPanel classes • How do we do this? • import java.applet.* • create a nested inner class that extends Applet, include an instance data of type AudioClip and in the Applet constructor, instantiate an Applet object: • aClip = Applet.newAudioClip(getClass( ).getResource(filename)); • add an accessor method to your Applet to return the audio clip • A skeleton of an example follows • NOTE: you can only hear wav files and you will only be able to hear them in the lab if you bring headphones
import java.applet.*; // needed to generate an AudioClip public class AudioExample2 { public static void main(String[] args) { AClip a = new AClip(); // create an Applet AudioClip c = a.getClip(); // use the Applet to generate an AudioClip c.play( ); // play the AudioClip } private static class AClip extends Applet // Applet as an inner class used to { // generate AudioClip objects private static AudioClip a; // Our AudioClip public AClip() // constructor { a = Applet.newAudioClip(getClass( ).getResource("chimes.wav")); } // getClass( ) returns the file location of this class // getResource returns the actual item, in this case a wav file public AudioClip getClip() // accessor { return a; } } } AudioClip Example