Continuous Play

Instead of just playing a sound once, you can load it into a java.applet.AudioClip object and play it continously with that interface's loop() method. First you have to download the sound into an AudioClip like this:

   AudioClip ac  = this.getAudioClip(new URL( 
      "http://metalab.unc.edu/javafaq/course/week9/spacemusic.au"));

Then, once you have the AudioClip object, merely invoke it's loop() method:

   ac.loop();

>When you're ready to stop playing the clip, invoke its stop() method like this

   ac.stop();

Here's the applet that's playing the music you're hearing now:

import java.applet.*;  // java.applet.Applet isn't enough


public class LoopApplet extends Applet {

  private AudioClip theSound;

  public void init() {
  
    String soundfile = this.getParameter("soundfile");
    if (soundfile != null) {
     theSound=this.getAudioClip(this.getDocumentBase(), soundfile);
    }
    
  }
  
  public void start() {
    if (theSound != null) theSound.loop();
  }

  public void stop() {
    if (theSound != null) theSound.stop();
  }

}

Notice in the applet above, that I take care to stop playing the music when the user leaves the page and the stop() method is invoked. Otherwise this could continue indefinitely until the user quit the web browser.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified March 5, 2002