Victor's Blog about the Web, Security and Life

The web for me is a hobby where standards and best practices are daily bread. Security is a concern that everybody must be aware of its details for IT in general, and the web in particular, to be a safer place. My life, on the other hand, is that of a regular Lebanese citizen where politics and social issues are discussed on a daily basis. I hope you enjoy reading my blog and make sure to drop me a comment about any topic you find interesting.

How To Play Audio Clips in Java Applications

Printable Version

victor | 24 January, 2007 16:03

It is well-know about the ease to play audio clips in Java when dealing with applets.

It is, however, hard to get a Java application to play audio clips because there is no such interface for audio clips.

In this article, I will demonstrate how to play audio clips.
To play clips, we must use some undocumented classes in Java.

import sun.audio.*; //import the sun.audio package
import java.io.*;
// 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);


Related Articles:

Comments

Sounds In Java

Tom | 19/04/2007, 12:38

Hi there, is there any possible way of playing sound using the Java API, as i a required to ONLY use these liberies???

Thanks in advance.
Tom.

thx

Jow | 18/04/2007, 06:48

Goood

Add comment
 
Accessible and Valid XHTML 1.0 Strict and CSS