tags:

views:

9959

answers:

4

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
Wow Greg.. I was gonna answer my own question and I finally did your answer was first.. :P Thank you.. ;)
pek
http://java.sun.com/products/jdk/faq/faq-sun-packages.html There are public API alternatives to using sun.audio.
McDowell
@GregHurlman Isn't sun.* package made to be not used by us developers?
Tom Brito
@Tom - Could be; I don't usually find myself using this sort of code.
Greg Hurlman
+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
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
+1 for a solution that uses the public API. Isn't creating a new thread unnecessary(redundant) though?
Jataro
Thanx..Is it redundant? I made it into a new thread so I can play the sound again before the first clip ends.
pek
I know clip.start() spawns a new thread, so I'm pretty sure it is unnecessary.
Jataro
+7  A: 

http://java.sun.com/docs/books/tutorial/sound/ is worth being the starting point

alex
+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