Recent articles:
Popular archives:
Java: A platform for platforms
Sun's reorg may seem promising to shareholders but it's also a scramble for position. The question now is whether Sun can,
or wants to, maintain its hold on Java technology. Especially with enterprise leaders like SpringSource and RedHat investing
heavily in Java's future as a platform for platforms
Also see:
Discuss: Java: A platform for platforms?
Playing audio clips in applets is quite simple and involves the following steps:
Here's how the code for these steps looks:
import java.applet.*; AudioClip ac = getAudioClip(getCodeBase(), soundFile); ac.play(); //play once ac.stop(); //stop playing ac.loop(); //play continuously
It would seem logical to use this same code to play audio clips in a Java application. Unfortunately, if you do that you will
get errors from the compiler. Why? Because the AudioClip object and the getAudioClip() method are part of the java.applet package -- and are not part of applications. The good news is we can dive down and make things work ourselves.
The trick to solving this problem is to use some undocumented features that are provided by Sun in its JDK. Taking a peek inside the classes.zip file from the Sun JDK (using any of the various zipfile utilities), we find not only the standard Java packages such as java.applet but also sun.audio. (These are in the directory sun/audio.)
The sun.audio package contains everything we need to be able to play audio clips! Here's the code:
import sun.audio.*; //import the sun.audio package import java.io.*; //** add this into your application code as appropriate // Open an input stream to the audio file. InputStream in = new FileInputStream(Filename); // Create an AudioStream object from the input stream. AudioStream as = new AudioStream(in); // Use the static class member "player" from class AudioPlayer to play // clip. AudioPlayer.player.start(as); // Similarly, to stop the audio. AudioPlayer.player.stop(as);
To use a URL as the audio stream source, substitute the following for the input stream and audio stream setup:
AudioStream as = new AudioStream (url.openStream());
Playing the audio stream continuously adds a bit more complexity:
// Create audio stream as discussed previously. // Create AudioData source. AudioData data = as.getData(); // Create ContinuousAudioDataStream. ContinuousAudioDataStream cas = new ContinuousAudioDataStream (data); // Play audio. AudioPlayer.player.play (cas); // Similarly, to stop the audio. AudioPlayer.player.stop (cas);
And there you have it. Remember, this technique uses undocumented features; there are no guarantees that it will work with anything but the current Sun JDK.
audio in application worksBy Anonymous on November 12, 2008, 2:03 amthanks!!! i have been looking for this because everyone just post about audio in applet this is great. Only the continous audio doesn't work it says that the method...
Reply | Read entire comment
View all comments