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, 2017 in CSC 211 (F17) by Robert (RJ) Nicholas (100 points)
edited Oct 8, 2017 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);

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, 2017 by Caleb Westerman (100 points)
selected Oct 12, 2017 by Robert (RJ) Nicholas