Skip to Main Content
Killer Game Programming in Java
book

Killer Game Programming in Java

by Andrew Davison
May 2005
Intermediate to advanced content levelIntermediate to advanced
998 pages
26h
English
O'Reilly Media, Inc.
Content preview from Killer Game Programming in Java

The AudioClip Class

Many of the shortcomings of Applet's play() method are remedied by the AudioClip class. AudioClip separates loading from playing and allows looping and termination via the loop() and stop() methods. Example 7-2 is an updated McDonald applet using AudioClip.

Example 7-2. Applet using the AudioClip class

import java.awt.*;
import javax.swing.*;
import java.applet.AudioClip;



public class McDonald extends JApplet
{
  private AudioClip mcdClip;

  public void init()
  {  mcdClip = getAudioClip(getCodeBase(), "mcdonald.mid");  }

  public void paint(Graphics g)
  {  g.drawString("Old McDonald", 25, 25);  }

  public void stop()
  {  mcdClip.stop(); }

  public void start()
  /* A looping play (and a call to play()) always starts at
     the beginning of the clip. */
  { mcdClip.loop();  }
} // end of McDonald class

The clip is loaded with getAudioClip() in init(), causing the applet to suspend until the download is completed. The sound is played repeatedly due to the loop() call in start(), continuing until the applet is removed from the browser (triggering a call to stop()). If the page is displayed again, start()'s call to loop() will play the music from the beginning.

An application employs AudioClips in just about the same way, except that the clip is loaded with newAudioClip() from the Applet class, as shown in the PlaySound application (see Example 7-3).

Example 7-3. Using newAudioClip() from an applet

import java.applet.Applet; import java.applet.AudioClip; public class PlaySound { public PlaySound(String ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Game Development with LibGDX: From Beginner to Professional

Java Game Development with LibGDX: From Beginner to Professional

Lee Stemkoski

Publisher Resources

ISBN: 0596007302Supplemental ContentErrata Page