0

How do we play sound (a music file of any format like .wma, .mp3 ) in a Java desktop application? (not an applet)

I have used the following code (taken from another question on Stack Overflow) but it throws an Exception.

public class playsound {
    public static void main(String[] args) {
s s=new s();
s.start();
    }
}
class s extends Thread{
    public void run(){
        try{
            InputStream in = new FileInputStream("C:\\Users\\srgf\\Desktop\\s.wma");
         AudioStream as =    new AudioStream(in); //line 26
            AudioPlayer.player.start(as);
        }
        catch(Exception e){
            e.printStackTrace();
            System.exit(1);
        }
    }
}

The program when run throws the following Exception:

java.io.IOException: could not create audio stream from input stream
    at sun.audio.AudioStream.<init>(AudioStream.java:82)
    at s.run(delplaysound.java:26)
Ranjith
  • 1,623
  • 3
  • 21
  • 34
  • Check http://stackoverflow.com/questions/5667454/playing-audio-file-in-java-application?rq=1 . I know it mentions mp3 isn't supported by JAVA, but could be same with .wma's considering windows isn't very nice. – Austin Sep 25 '12 at 06:33

3 Answers3

0

Use this library: http://www.javazoom.net/javalayer/javalayer.html

public void play() {
        String song = "http://www.ntonyx.com/mp3files/Morning_Flower.mp3";
        Player mp3player = null;
        BufferedInputStream in = null;
        try {
          in = new BufferedInputStream(new URL(song).openStream());
          mp3player = new Player(in);
          mp3player.play();
        } catch (MalformedURLException ex) {
        } catch (IOException e) {
        } catch (JavaLayerException e) {
        } catch (NullPointerException ex) {
        }

}

Hope that helps everyone with a similar question :-)

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • Can the above code also play files from the hard disk? It's not working for me. I included the above code in the run() method of a Thread and after the statement mp3player.play(), I included the statement sleep(10000); so that the audio completes playing. – Ranjith Sep 25 '12 at 06:46
  • Yes see this example http://thiscouldbebetter.wordpress.com/2011/06/14/playing-an-mp3-from-java-using-jlayer/ – Zaheer Ahmed Sep 25 '12 at 06:52
0

Hmmm. This might look like advertisement for my stuff, but you could use my API here:

https://github.com/s4ke/HotSound

playback is quite easy with this one.

Alternative: use Java Clips (prebuffering)

... code ...
// specify the sound to play
File soundFile = new File("pathToYouFile");
//this does the conversion stuff for you if you have the correct SPIs installed
AudioInputStream inputStream = 
getSupportedAudioInputStreamFromInputStream(new FileInputStream(soundFile));

// load the sound into memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);

// due to bug in Java Sound, explicitly exit the VM when
// the sound has stopped.
clip.addLineListener(new LineListener() {
  public void update(LineEvent event) {
    if (event.getType() == LineEvent.Type.STOP) {
      event.getLine().close();
      System.exit(0);
    }
  }
});

// play the sound clip
clip.start();
... code ...

Then you need this method:

public static AudioInputStream getSupportedAudioInputStreamFromInputStream(InputStream pInputStream) throws UnsupportedAudioFileException,
        IOException {
    AudioInputStream sourceAudioInputStream = AudioSystem
            .getAudioInputStream(pInputStream);
    AudioInputStream ret = sourceAudioInputStream;
    AudioFormat sourceAudioFormat = sourceAudioInputStream.getFormat();
    DataLine.Info supportInfo = new DataLine.Info(SourceDataLine.class,
            sourceAudioFormat,
            AudioSystem.NOT_SPECIFIED);
    boolean directSupport = AudioSystem.isLineSupported(supportInfo);
    if(!directSupport) {
        float sampleRate = sourceAudioFormat.getSampleRate();
        int channels = sourceAudioFormat.getChannels();
        AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                sampleRate,
                16,
                channels,
                channels * 2,
                sampleRate,
                false);
        AudioInputStream convertedAudioInputStream = AudioSystem
                .getAudioInputStream(newFormat, sourceAudioInputStream);
        sourceAudioFormat = newFormat;
        ret = convertedAudioInputStream;
    }
    return ret;
}

Source for the Clip example (with little changes by me): http://www.java2s.com/Code/Java/Development-Class/AnexampleofloadingandplayingasoundusingaClip.htm

SPIs are added via adding their .jars to the classpath

for mp3 these are:

Martin Braun
  • 602
  • 10
  • 28
0

Using JavaFX (which is bundled with your JDK) is pretty simple. You will need the following imports:

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;

import java.nio.file.Paths;

Steps:

Initialize JavaFX:

new JFXPanel();

Create a Media (sound):

Media media = new Media(Paths.get(filename).toUri().toString());

Create a MediaPlayer to play the sound:

MediaPlayer player = new MediaPlayer(media);

And play the Media:

player.play();

You can set the start/stop times as well with MediaPlayer.setStartTime() and MediaPlayer.setStopTime():

player.setStartTime(new Duration(Duration.ZERO)); // Start at the beginning of the sound file
player.setStopTime(1000); // Stop one second (1000 milliseconds) into the playback

Or, you can stop playing with MediaPlayer.stop().

A sample function to play audio:

public static void playAudio(String name, double startMillis, double stopMillis) {
    Media media = new Media(Paths.get(name).toUri().toString());
    MediaPlayer player = new MediaPlayer(media);

    player.setStartTime(new Duration(startMillis));
    player.setStopTime(new Duration(stopMillis));
    player.play();
}

More info can be found at the JavaFX javadoc.

codecubed
  • 780
  • 7
  • 8