I want to be able to play sound files in my program. Where should I look?
+10
A:
A simple example:
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);
Greg Hurlman
2008-08-25 16:01:58
Wow Greg.. I was gonna answer my own question and I finally did your answer was first.. :P Thank you.. ;)
pek
2009-02-23 20:26:17
http://java.sun.com/products/jdk/faq/faq-sun-packages.html There are public API alternatives to using sun.audio.
McDowell
2009-04-23 13:44:06
@GregHurlman Isn't sun.* package made to be not used by us developers?
Tom Brito
2010-06-10 14:00:07
@Tom - Could be; I don't usually find myself using this sort of code.
Greg Hurlman
2010-06-12 17:49:36
+7
A:
I personally made this code that works fine. I think it only works with .wav format.
public static synchronized void playSound(final String url) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("/path/to/sounds/" + url));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}).start();
}
pek
2008-08-25 16:03:41
To avoid Clip being shut down at random time, a LineListener is required. Have a look: http://stackoverflow.com/questions/577724/trouble-playing-wav-in-java/577926#577926
alex
2009-02-23 15:40:31
+1 for a solution that uses the public API. Isn't creating a new thread unnecessary(redundant) though?
Jataro
2009-07-29 09:09:27
Thanx..Is it redundant? I made it into a new thread so I can play the sound again before the first clip ends.
pek
2009-07-29 19:04:36
I know clip.start() spawns a new thread, so I'm pretty sure it is unnecessary.
Jataro
2009-07-29 20:20:20
+7
A:
http://java.sun.com/docs/books/tutorial/sound/ is worth being the starting point
alex
2009-02-22 15:32:20
+1
A:
There is an alternative to importing the sound files which works in both applets and applications: convert the audio files into .java files and simply use them in your code.
I have developed a tool which makes this process a lot easier. It simplifies the Java Sound API quite a bit.
http://stephengware.com/projects/soundtoclass/
Hope this helps. -- Stephen
Stephen Ware
2010-01-18 06:34:06