Java Reference
In-Depth Information
Playing an Audio/Sound File
Problem
You want a quick and easy way to “make noise” or play an existing sound file.
Solution
Use the Audio API.
Discussion
This might seem out of place in the midst of all this Graphics code, but there's a pattern.
We're moving from the simpler graphical forms to more dynamic multimedia. You can play
audio file using an AudioClip to represent it:
public
public class
class AudioPlay
AudioPlay {
static
static String defSounds [] = {
"/audio/test.wav" ,
"/music/midi/Beet5th.mid" ,
};
public
public static
void main ( String [] av ) {
iif ( av . length == 0 )
main ( defSounds );
static void
else
else for ( String a : av ) {
System . out . println ( "Playing " + a );
try
try {
URL snd = AudioPlay . class . getResource ( a );
iif ( snd == null
null ) {
System . err . println ( "Cannot getResource " + a );
continue
continue ;
}
AudioInputStream audioInputStream =
AudioSystem . getAudioInputStream ( snd );
final
final Clip clip = AudioSystem . getClip ();
clip . open ( audioInputStream );
clip . start ();
} catch
catch ( Exception e ) {
System . err . println ( e );
Search WWH ::




Custom Search