[Document Introduction] In some cases, an event may need to be accompanied by a sound, indicating that the sound is played when the image is loaded in the Applet, this greatly enriches the Applet content.
In some cases, an event may need to be accompanied by a sound, indicating that the sound is played when the image is loaded in the Applet, which greatly enriches the Applet content. It is very important to coordinate the use of images.
Sound and image coordination (Appletl. java)
// Source code list
Import java. awt .*;
Import java. applet .*;
Import java. util .*;
Public class Appletl extends Applet implements Runnable
{
AudioClip audioClip;
Thread ShapeThread = null;
Random RandomNumber = new Random ();
Color ImageColor;
Public void init ()
{
AudioClip = getAudioClip (getCodeBase (), "Sample. AU"); // create an AudioClip object
}
Public void start ()
{
If (ShapeThread = null)
{
ShapeThread = new Thread (this );
ShapeThread. start ();
}
}
Public void run ()
{
While (true)
{
Switch (RandomNumber. nextlnt (5) {// convert a random number to 0 ~ Value between 4
Case 0: ImageColor = Color. black;
Break;
Case 1: ImageColor = Color. blue;
Break;
Case 2: ImageColor = Color. cyan;
Break;
Case3: ImageColor = Color. magenta;
Break;
Case4: ImageColor = Color. orange;
Break;
Default: ImageColor = Color. red;
}
Try
{
ShapeThread. sleep (300); // thread sleep
}
Catch (InterruptedException e)
{
// Ignore an exception
Repaint ();
}
}
Public void paint (Graphics g)
{
G. setColor (ImageColor );
AudioClip. play (); // playback sound
Switch (RandomNumber. nextlnt (2) // obtain the remainder of the random number and Division 2
{
Case0: g. fillRect (25, 25, 200,200); // Add a rectangle
Break;
Default: g. fillOval (200,200,); // Add an elliptic
Break;
}
}
}
The sound processing of this Applet is very simple. It first creates an AudioClip object and uses getAudioClip to assign the sound file to the object, and then plays the sound using the play method of the AudioClip class. The Applet uses the Random object to generate a Random number. It first determines the color based on the random number, and then determines whether the circle or the painting side is based on the random number in the paint. The nexsInt function of the Random class returns a Random INTEGER (int type ). This Applet converts a random number to a 0 ~ The value between 4 (in the run function) and a 0 ~ Value Between 1 (in the paint function ).
Put the following HTML statement into the Appletl. HTML file to prepare for running the Appletl.
<HTML>
<TITLE>Applet</TITLE>
<APPLET CODE="Appletl.class" WIDTH=300 HEIGHT=300>
</APPLET>
</HTML>