Applet PlayingThe Applet play( ) method loads a sound (perhaps from across the network) and plays it once. play( ) causes the applet's drawing and event handling to freeze while the audio data are retrieved and does nothing if the audio can't be found (i.e., no exception is raised). The sound is marked for garbage collection after being played, so it may need to be downloaded again when play( ) is called again. Example 7-1 is a typical 1990s example: Example 7-1. Simple applet that uses the play( ) method import java.applet.Applet; import java.awt.*; public class OldMcDonald extends Applet { public void init( ) {play( getCodeBase( ), "McDonald.mid"); } public void paint(Graphics g) { g.drawString("Older McDonald", 25, 25); } } // end of OldMcDonald class The MIDI file (containing the tune "Old McDonald") is loaded and played as the applet is loaded. getCodeBase( ) indicates that the file can be found in the same place as the applet's .class file. An alternative is getdocumentBase( ), which specifies a location relative to the enclosing web page.
Early versions of Java only supported 8-bit mono Windows Wave files, but the various formats were extended in JDK 1.2 to include Sun Audio (AU files), Mac AIFF files, Musical Instrument Digital Interface (MIDI) files (type 0 and type 1), and Rich Media Format (RMF). Data can be 8-bit or 16-bit, mono or stereo, with sample rates between 8,000 and 48,000 Hz. |