I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.
public void play()
{
String song = "song.mp3";
Media track = new Media(song);
MediaPlayer mediaPlayer = new MediaPlayer(track);
mediaPlayer.play();
}
I have tried doing that but it gives me errors.
I have imported JMF and JLayer.
I have also read other questions that are like this one on this forum and none of them have helped me.
I just need a hand to help play an mp3 file.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
}catch(Exception e){System.out.println(e);}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
For this you'll need to install Java Media Framework (JMF) in your PC. One you have it installed,then try this piece of code:
import javax.media.*;
import java.net.*;
import java.io.*;
import java.util.*;
class AudioPlay
{
public static void main(String args[]) throws Exception
{
// Take the path of the audio file from command line
File f=new File("song.mp3");
// Create a Player object that realizes the audio
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
// Start the music
p.start();
// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);
// Read a line and store it in st
String st=s.nextLine();
// If user types 's', stop the audio
if(st.equals("s"))
{
p.stop();
}
}
}
You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a “JMF MP3 plugin” in order to play MP3 file.
Go Java’s JMF website to download it
http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html
To be sure that you are using a supported format file, check here:
http://www.oracle.com/technetwork/java/javase/formats-138492.html
If you are using windows7, you may have to read this as well:
https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45
How about JavaFX application-
import java.net.URL;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class VLC extends Application {
void playMedia() {
String mp3 = "00- Tu Hi Mera.mp3";
URL resource = getClass().getResource(mp3);
System.out.println(resource.toString());
Media media = new Media(resource.toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
public static void main(String args[]) {
new VLC().playMedia();
}
#Override
public void start(Stage stage) throws Exception {
}
}
Related
Trying to loop an audio clip. Look right but i hear nothing.
Does local audio clip have to have the extension ".au"? or can i play aiff, mp3 or wav for example?
I'm really sorry if this is not properly explaned. I'm really new to this.
Tried to play sounds on my hard drive (.wav) (put in the same folder as my java program) AND of the internet.
An input dialog pops up and asks for an audio clip. Works fine. Here the user is supposed to write either a local file name or a web address.
I write (for local files) "file:myAudioclip.wav" or (for internet) "https://www....) but nothing plays.
import java.applet.*; //Importerar necessary packages
import java.net.*;
import javax.swing.*;
public class AudioClip2 {
public static void main(String[] args) throws
MalformedURLException, InterruptedException {
// Handling errors
String filnamn = JOptionPane.showInputDialog("Audio clip?");
// This is where I write what clip I wanna play
URL u = new URL(filnamn);
// Create a URL for my clip
AudioClip a = Applet.newAudioClip(u);
a.loop();
//Looping AudioClip a
Thread.sleep(10000); //Create a paus (ignore)
}
}
I searched in many forums and YouTube tutorials for an easy bit of code to just play a sound file (.mp3), but everything I found won't work for me.
I always get the exception that it can't find the file or that something else is wrong, but it always ends in an exception.
Is there something that I have to configure first maybe?
-edit-
I tried the following code again to show what exeption i get:
Here is my code
After adding the JFXPanel i got the exeption: Exception in thread "main" MediaException: MEDIA_UNAVAILABLE : D:\bip.mp3 (The System cant find the File) //
and yes, i checked if the path is correct.
To avoid initialization Exception you have to either invoke Application.launch() method or simply instantiate a new JFXPanel() class (even if it isn’t used for anything). This will initiate JavaFxRuntime when application is started
so add below line in your code
final JFXPanel fxPanel = new JFXPanel();
Import following package
import javafx.embed.swing.JFXPanel;
Now your code will look like this
import java.io.File;
import javafx.embed.swing.JFXPanel;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class Test {
public static void main(String args[]) {
final JFXPanel fxPanel = new JFXPanel();
String bip = "D://bip.mp3"; //sound file path
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}
}
Maybe posting a specific error can solve your problem but anyways I think this can help you. And also I implemented it and works perfectly for me.
This is how I have done it:
List<Media> mediaList = new ArrayList<>();
FileManager files = new FileManager();
files.loadMediaFiles(new File("your music directory goes here.."));
files.getFiles().stream().forEach((media) -> {
mediaList.add(new Media(media));
});
MediaPlayer mediaPlayer = new MediaPlayer(playList.get(0));
MediaView mediaView = new MediaView(mediaPlayer);
playPauseButton.setOnAction((ActionEvent event) -> {
if (mediaPlayer.getStatus() == Status.PAUSED || mediaPlayer.getStatus() == Status.READY || mediaPlayer.getStatus() == Status.STOPPED) {
mediaPlayer.play();
playPauseButton.setGraphic(pause);
} else {
mediaPlayer.pause();
playPauseButton.setGraphic(play);
}
});
You can also checkout my app on github.
This question already has answers here:
How to have the user choose an audio file and play it in Java
(2 answers)
Closed 9 years ago.
I've got a problem with this Code..
I tried to play some sound, which is in the Musik directory in Eclipse. I already tested, if the sound exist, can be read, and can be opened. All looks ok. But I can't hear anything.
package mhm;
import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
new Main();
}
URL url = null;
AudioClip clip;
File file = new File("Musik/VOWZN-UnRational.wav");
public Main() {
try {
url = new URL("file://" + file.getPath());
} catch (MalformedURLException e) {
e.printStackTrace();
}
clip = Applet.newAudioClip(url);
clip.play();
new Menu();
}
}
On Runtime, there aren't any errors..
That code should not work in an (untrusted) applet. It is trying to access a file in the local filesystem (via a "file:" URL), and sandbox security should block that.
Im using Windows 7 and can "Java Platform SE Binary" in my sound mixer but yet still no sound seems to play.
My code is:
import javax.media.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLExc;
public class SimpleAudioPlayer {
private Player audioPlayer = null;
public SimpleAudioPlayer(URL url) throws IOException, NoPlayerException,
CannotRealizeException {
audioPlayer = Manager.createRealizedPlayer(url);
}
public SimpleAudioPlayer(File file) throws IOException, NoPlayerException,
CannotRealizeException {
this(file.toURL());
}
public void play() {
audioPlayer.start();
}
public void stop() {
audioPlayer.stop();
audioPlayer.close();
}
public static void main(String[] args) {
try{
File audioFile = new File("/t.mp3");
SimpleAudioPlayer player = new SimpleAudioPlayer(audioFile);
System.out.println();
System.out.println("-> Playing file '" +
audioFile.getAbsolutePath() + "'");
System.out.println(" Press the Enter key to exit");
player.play();
// wait for the user to press Enter to proceed.
System.in.read();
System.out.println("-> Exiting");
player.stop();
}catch(Exception ex){
ex.printStackTrace();
}
System.exit(0);
}
}
I use the Windows Preformance JMF edition. The MP3 im trying to play works fine in VLC/WMP so it cant be the file.
The code also throws no exceptions or error when running, it just doesnt seem to play the sound.
Is there something im missing? Like pulling the sound card? E.g. taking over it so i can play sound out of it?
Im overall aim is to to a MP3 streaming service using RTP/RTSP so any links,advice or tuturiols would be help as im currelnt using IBM JMF Tuturiol and Java Demo
Please ask if any more information is needed!
UPDATE-
Downloaded WAV FILE and it seemed to play, how can i make MP3s play?
Added formats and tried this code and still the same issue:
import java.io.File;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;
public class SimpleAudioPlayer {
public static void main(String[] args) {
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
try {
Player player = Manager.createPlayer(new MediaLocator(new File("/t.mp3").toURI().toURL()));
player.start();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
Unable to handle format: mpeglayer3, 44100.0 Hz, 16-bit, Stereo, LittleEndian, Signed, 16000.0 frame rate, FrameSize=32768 bits
Failed to realize: com.sun.media.PlaybackEngine#62deaa2e
Error: Unable to realize com.sun.media.PlaybackEngine#62deaa2e
Thats the error!
As I thought, it's a missing codec.
I think this is what you need: http://www.oracle.com/technetwork/java/javase/download-137625.html
I have this code :
package test;
import java.io.File;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;
public class AudioTest {
public static void main(String[] args) {
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
try{
Player player = Manager.createPlayer(new MediaLocator(new File("1.mp3").toURI().toURL()));
player.realize();
player.start();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
i'm trying to play an mp3 file, mp3plugin is added to the project lib as well as the jmf jar.
there's no error on the console but cant hear a sound.
the file is not playing.
.wav files are playing fine.
any idea ?
JMF is a bad option. The project was abandoned long time ago.
I have answered a similar question here:
Java - Error when trying to use mp3plugin for playing an mp3 file
it might be usefull for you - Im using Java Sound
The following is all I need to play music.
public static void main(String args[]) throws NoPlayerException, CannotRealizeException, IOException {
MediaLocator ml = new MediaLocator((new File("roar_of_future.mp3").toURL()));
Player player = Manager.createRealizedPlayer(ml);
player.start();
}
So please make sure mp3plugin.jar is in the classpath and your javasdk is Java 8 (32bit) or 7 (32bit) because JMF is not working on Java 9 and above.