Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Play music in Java?

+5 votes
Is there a way to have Java play something like an .mp3 file? I was thinking of maybe adding sound effects and/or background music to the project if possible.
asked Oct 7 in CSC 211 (F17) by Robert (RJ) Nicholas (1,912 points)
edited Oct 8 by Robert (RJ) Nicholas

1 Answer

+1 vote
 
Best answer

Java FX has Media and MediaPlayer classes which will play mp3 files.

Example code:

String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();

You will need the following import statements:

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

Source: https://stackoverflow.com/questions/6045384/playing-mp3-and-wav-in-java

Alternative: https://stackoverflow.com/questions/19603450/how-can-i-play-an-mp3-file

You MAY need to download the proper libraries to eclipse to make sure you are able to import them properly! 

answered Oct 12 by Caleb Westerman (1,448 points)
selected Oct 12 by Robert (RJ) Nicholas
...