How to play a sound file in Java - java

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.

Related

how to use vlcj with java?

Hello Everyone i'm trying to use vlcj for java but am running into a lot of errors. I checked my jvm version and vlc media version both are 64 bit.
I tried a lot of codes that I had researched in the internet. I followed the step by inserting vlcj.jar in my code but nothing seems to work.
I followed the tutorial on caprica but it wouldn't work. Now i'm getting error
Exception in thread "main" java.lang.IllegalArgumentException: Interface (LibVlc) of library=libvlc does not extend Library B.
Can someone please help on this?
package mrbool.vlc.example;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.factory.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.binding.LibVlc;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import uk.co.caprica.vlcj.binding.RuntimeUtil;
public class JavaApplication1 {
public static void main(String[] args) {
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),"C:\\Program Files\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
MediaPlayerFactory factory = new MediaPlayerFactory();
}
}
install vlc media player in to same directory that your project is located
Sometimes the problem is due to incompatibility of the architecture of VLC and JRE.
You can check JRE architecture using the code below:
public class JavaApplication12 {
public static void main(String[] args) {
System.out.println(System.getProperty("sun.arch.data.model"));
}
}
EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
EmbeddedMediaPlayer embeddedMediaPlayer = mediaPlayerComponent.getMediaPlayer();
Canvas videoSurface = new Canvas();
videoSurface.setBackground(Color.black);
videoSurface.setSize(800, 600);
List<String> vlcArgs = new ArrayList<String>();
vlcArgs.add("--no-plugins-cache");
vlcArgs.add("--no-video-title-show");
vlcArgs.add("--no-snapshot-preview");
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory(vlcArgs.toArray(new String[vlcArgs.size()]));
mediaPlayerFactory.setUserAgent("vlcj test player");
embeddedMediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(videoSurface));
embeddedMediaPlayer.setPlaySubItems(true);
final PlayerControlsPanel controlsPanel = new PlayerControlsPanel(embeddedMediaPlayer);
PlayerVideoAdjustPanel videoAdjustPanel = new PlayerVideoAdjustPanel(embeddedMediaPlayer);
// mediaPlayerComponent.getMediaPlayer().playMedia(Constant.PATH_ROOT + Constant.PATH_MEDIA + "tmp.mp4");
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.setBackground(Color.black);
mainFrame.add(videoSurface, BorderLayout.CENTER);
mainFrame.add(controlsPanel, BorderLayout.SOUTH);
mainFrame.add(videoAdjustPanel, BorderLayout.EAST);
//create a button which will hide the panel when clicked.
mainFrame.pack();
mainFrame.setVisible(true);
embeddedMediaPlayer.playMedia("tmp.mp4");
Also, to do this yourself I would suggest using chrome. You just right click on whatever you want to scrape and go to inspect element. It will take you to the exact spot in the html where that element is located. In this case you first want to find out where the root of all the result listings are. When you find that, you want to specify the element, and preferably an unique attribute to search it by. In this case the root element i
public class ScanWebSO
{
public static void main (String args[])
{
Document doc;
try{
doc = Jsoup.connect("https://www.google.com/search?as_q=&as_epq=%22Yorkshire+Capital%22+&as_oq=fraud+OR+allegations+OR+scam&as_eq=&as_nlo=&as_nhi=&lr=lang_en&cr=countryCA&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=&as_rights=").userAgent("Mozilla").ignoreHttpErrors(true).timeout(0).get();
Elements links = doc.select("li[class=g]");
for (Element link : links) {
Elements titles = link.select("h3[class=r]");
String title = titles.text();
Elements bodies = link.select("span[class=st]");
String body = bodies.text();
System.out.println("Title: "+title);
System.out.println("Body: "+body+"\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}

javascript error"java.lang.NullPointerException" in netbeans

Im trying to use javascript with netbeans. Im supposed to make a mastermind game using javascript. when ı tried to add something to .js ı always have this error;
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at assgn1.Main.main(Main.java:32)
ı couldnt figur out why. thanks for any help.
my codes are;
Main.java
package assgn1;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) throws ScriptException {
// TODO code application logic here
// create manager
ScriptEngineManager m = new ScriptEngineManager();
// create javascript script engine
ScriptEngine js = m.getEngineByName("javascript");
// evaluate "hello.js"
InputStream strm = Main.class.getResourceAsStream("/hello.js");
Reader r = new InputStreamReader(strm);
js.eval(r);
}
}
hello.js
importPackage(javax.swing);
importClass(java.lang.System);
function exit(){
System.exit(0);
}
var f= new JFrame("MasterMind");
var b= new JButton("exit");
b.addActionListener(exit);
f.add(path);
f.add(b,"South");
f.setSize(800,800);
f.visible=true;
You should check if
InputStream strm = Main.class.getResourceAsStream("/hello.js");
doesnt return a null object because the path is wrong. Seems like you get the NullPointerException because of that.

Set Icon Image in Java

I have been searching everywhere on how to set the icon image in Java, and it always ends up not working or it gives me errors. Here, in my main method is where I put the code:
public static void main(String[] args) {
Game game = new Game();
// This right here!
game.frame.setIconImage(new ImageIcon("/Icon.png").getImage());
game.frame.setResizable(false);
game.frame.setTitle(title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
}
My path for the image is "%PROJECT%/res/Image.png" and I just use /Image.png to go ahead and access my res folder (as I have done in other parts of my project) I have even converted it into an icon file, and tried that, but all it decides is to use the default Java icon.
Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.
e.g.,
// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);
// use icon here
game.frame.setIconImage(myImg);
Use Default toolkit for this
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:
IconImageUtilities.setIconImage(this);
The below method works well on Java 7 and above.
JFrame frame = new JFrame("MyAPP");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
frame.setIconImage(ImageIO.read(YourClass.class.getResourceAsStream("/icon.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
frame.setVisible(true);
Park your icon.png image file to /src/main/resources.

How to play an mp3 file in java

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 {
}
}

JMF + mp3plugin.jar mp3 files is not playing

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.

Categories