0

What is the simples way to add music to my JFrame ? I've tried this :

    Clip clip = AudioSystem.getClip();
    AudioInputStream ais = AudioSystem.getAudioInputStream(new File( "song.mp3") );
    clip.open(ais);
    clip.loop(Clip.LOOP_CONTINUOUSLY);
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            // A GUI element to prevent the Clip's daemon Thread 
            // from terminating at the end of the main()
            JOptionPane.showMessageDialog(null, "Close to exit!");
        }
    });

But it give me some sintax errors.

AXL
  • 17
  • 1
  • 6

1 Answers1

0

It's difficult to be 100% sure, but it would appear that you are ignoring, but you appear to be ignoring the exceptions thrown be various classes/methods, as the rest of the code seems to work okay...

try {
    Clip clip = AudioSystem.getClip();
    AudioInputStream ais = AudioSystem.getAudioInputStream(new File("song.mp3"));
    clip.open(ais);
    clip.loop(Clip.LOOP_CONTINUOUSLY);
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
                // A GUI element to prevent the Clip's daemon Thread 
            // from terminating at the end of the main()
            JOptionPane.showMessageDialog(null, "Close to exit!");
        }
    });
} catch (LineUnavailableException | UnsupportedAudioFileException | IOException ex) {
    ex.printStackTrace();
}

Now, the other problem is, by default, Java Audio won't play MP3 files. You can add support by including the mp3plugin.jar from the Java Media Framework, check out Playing MP3 using Java Sound API for more details

Another option is to use the MP3SPI supplied by JavaZoom, but they also have there own audio API, JLayer which has worked well for me in the past

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I am getting syntax error on the line at top of try block : Syntax error on token ";", { expected after this token – AXL Feb 04 '15 at 07:18