Consider the following code for an Applet:
import java.applet.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Audioapp extends JApplet
{
public class Sound // Holds one audio file
{
private AudioClip song; // Sound player
private URL songPath; // Sound path
Sound(String filename)
{
try
{
songPath = new URL(getCodeBase(),filename); // Get the Sound URL
song = Applet.newAudioClip(songPath); // Load the Sound
}
catch(Exception e){} // Satisfy the catch
}
public void playSound()
{
song.loop(); // Play
}
public void stopSound()
{
song.stop(); // Stop
}
public void playSoundOnce()
{
song.play(); // Play only once
}
}
public void init()
{
Sound testsong = new Sound("song.mid");
testsong.playSound();
}
}
An AudioClip is an Applet thing, so you need to "import java.applet.*". The part of the code you should focus on is the Sound class:
public class Sound // Holds one audio file
{
private AudioClip song; // Sound player
private URL songPath; // Sound path
Sound(String filename)
{
try
{
songPath = new URL(getCodeBase(),filename); // Get the Sound URL
song = Applet.newAudioClip(songPath); // Load the Sound
}
catch(Exception e){} // Satisfy the catch
}
public void playSound()
{
song.loop(); // Play
}
public void stopSound()
{
song.stop(); // Stop
}
public void playSoundOnce()
{
song.play(); // Play only once
}
}
It has an AudioClip and a URL class. The URL is needed to locate the file in question. Next:
Sound(String filename)
{
try
{
songPath = new URL(getCodeBase(),filename); // Get the Sound URL
song = Applet.newAudioClip(songPath); // Load the Sound
}
catch(Exception e){} // Satisfy the catch
}
The getCodeBase gets the path of whever the JAVA code class is. The URL constructor simply gets that URL and adds the filename to your sound file at the end. Then
song = Applet.newAudioClip(songPath); // Load the Sound
Creates the new AudioClip so you can play sounds. The rest of the class is just three simple methods:
public void playSound()
{
song.loop(); // Play
}
public void stopSound()
{
song.stop(); // Stop
}
public void playSoundOnce()
{
song.play(); // Play only once
}
These are quite self-explaining. playSound loops the sound, stopSound stops the sound, and playSoundOnce is good for sound effects because it only plays the file once.
That's it! LOL! Yes, that's right, that's all you need to play sound files! In some other languages, the tutorials stretch on for pages but this one is really short! I can't belive how simple it was to do all of this! It even handles all the sound-based problems!
You don't need to make several Sound objects of the same sound to have them play at the same time, you can just call one Sound object's playSoundOnce method several times! It plays them all together! MIDIs are no problem, just load a MIDI and call playSound! And when the music should stop, call stopSound!
Just put the object in the JAVA applications in which you want to have sound played in!








MultiQuote









|