I'm trying to make simple audio player with JavaFX Mediaplayer component. All local files are fine but i want also implement internet radio.
Code:
public static void main(String[] args) throws URISyntaxException {
new JFXPanel(); //init jfx library
String u = "http://91.121.164.186:8050";
Media m=null;
try {
m = new Media(u);
} catch (MalformedURLException e) {
e.printStackTrace();
}
MediaPlayer player = new MediaPlayer(m);
System.out.println("play");
player.play();
player.setVolume(new Double(1));
}
When I run it like this there is no errors but there is no audio. What's wrong ? What are other posibilities to play radio stream in Java ?
In your current example I can see two errors,
You are trying to run a JAVAFX component on a non-Javafx thread, which will result in error. Try running your program inside the start method. Please go through How to use JavaFX MediaPlayer correctly?
The URL you are trying to access must be a Media Compoenent
Try going through this extremely great example on Javafx Media
http://docs.oracle.com/javafx/2/media/EmbeddedMediaPlayer.zip
N.B. The example has lot more data than your require, but its a great example !
"http://91.121.164.186:8050" is a website, (HTML document), not a audio file. You need to download an audio file, something that the player knows what to do with.
Related
I'm creating a video player using JavaFX media player library. I need to retrieve the metadata and display in a window. I'm having problems retrieving the data though.
I've read 2 threads about this already and I understand that this is done asynchronously so I need a listener in order to get the metadata.
First Thread:Retrieving metadata from media files in JavaFX
Second Thread: https://stackoverflow.com/a/43144197/12787326
This code has been implemented like so below.
public void initialize(URL location, ResourceBundle resources) {
//Initialising path of the media file, replace this with your file path
String path = "Video.mp4";
//Instantiating Media class
Media media = new Media(new File(path).toURI().toString());
//Listener
media.getMetadata().addListener((MapChangeListener<String,Object>) change-> {
System.out.println(change);
});
//Instantiating MediaPlayer class
mediaPlayer = new MediaPlayer(media);
mv.setMediaPlayer(mediaPlayer);
mediaPlayer.setOnReady(() -> {
...
mediaPlayer.play();
});
}
I have tried a variety of different changes to the listener such as placing it in different areas of the code and trying to get the data from the mediaPlayer, which accesses the media itself. None of these seems to have fixed the problem.
I've tried print statements in the code trying to print off the contents of media.getMetadata but all I get is an empty list back.
I've tried creating a listener for media.getTracks() and that works as expected with updating each time the player switches its status. So that makes me wonder what is going wrong with media.getMetadata()
This is what the metadata of the video currently looks like so I assume I should be getting this infomarmation
I think the listener isn't seeing anything change, that's why print(change) is never reached. However, even if that is true, shouldn't me doing a system.out.print(media.getMetaData()) in the setOnAction code give me the data? Because when I try that all I get is an empty list.
Does anyone know how to fix this or tell me what I'm doing wrong?
I'm using NetBeans and trying to make a Jbutton play this .wav file that I have located in the build/classes/shadow part of my project. I want the .Jar to build with the .wav file so I could download the .Jar file on another computer and press the button and the music will play. The music is not locating or starting I'm not sure which it is, also please be easy on the terminology I am very very new.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:File Clap = new File("sanic.WAV");
display.setText("cum on step it up!!!");
}
public static void startMusic() {
{
try{
URL url = Shadow.class.getClassLoader().getResource("sanic.wav");
play(); // NetBeans says it cannot find the symbol for play.
}catch(Exception e){
}
}
}
I'm not sure in what part of your code are you using your URL... But I'd suggest you to use AudioInputStream...
Regarding the problem finding the file... I had implemented something similar some time ago, while checking the code I have in my HDD, I found that this made it for me:
URL url = Shadow.class.getResource(myfile.wav);
But nowadays, I prefer working with this:
InputStream resourceAsStream = Shadow.class.getResourceAsStream(myfile.wav);
Hope it helps for what you need to do.
Regards and... happy coding :)
I have spent hours today looking up how to get some form of audio in eclipse and have had trouble every step of the way. Currently I have something that should work but I get an error:
Exception in thread "main" java.lang.IllegalArgumentException: expected file name as argument
at com.sun.javafx.css.parser.Css2Bin.main(Css2Bin.java:44)
I have basically copied this from someone who had it working. I would like to say that the FX lib is added where it should be. I know this isn't fancy but I was just trying the basics.
package b;
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class test {
public static void main(String[] args){
String uriString = new File("C:\\Users\\Mike\\workspace\\b\\src\\hero.mp3").toURI().toString()
MediaPlayer player = new MediaPlayer( new Media(uriString));
player.play();
}}
I have also tried many different path names in case it was wrong with no luck, I also just tried to copy and paste the path name that i got in eclipse by going to properties ex: /b/src/hero.mp3. Help would be appreciated to get me out of this nightmare.
The files located outside the workspace should be included with file:// prefix. A simple example demonstrating the functionality is
public class Reproductor extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
Media media = new Media("file:///Movies/test.mp3"); //replace /Movies/test.mp3 with your file
MediaPlayer player = new MediaPlayer(media);
player.play();
}
}
If the file is into the resources/music this will work and the application will be portable,.mp3 inside the .jar:
Media media = null;
try {
media = new Media(getClass().getResource("/music/hero.mp3").toURI().toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
I suspect you have a issue with referencing embedded resources. An embedded resource is any file which is contained within the application context (ie. In this case, stored within the application Jar).
In order to obtain a reference to these resources, you need to use Class#getResource, which returns a URL, which you can then use to load the resource depending on your requirements, for example...
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
String path = Test.class.getResource("/Kalimba.mp3").toString();
Media media = new Media(path);
MediaPlayer mp = new MediaPlayer(media);
mp.play();
System.out.println("Playing...");
}
public static void main(String[] args) {
launch(args);
}
}
Now, I couldn't get it to work until I wrapped in a Application context...
JavaFX EMBED an MP3 into the jar (in the jar) with NetBeans
I programmed my very first JavaFX package in NetBeans, and then I wanted to add sound, an mp3 music file, embedded in the jar, inside the jar, so that I could email the jar to my friends and the music would play on their computers. Thank you StackOverflow for your help. Thanks especially to the member who said “put your music file IN THE JAR, getResourceAsStream() is the API you want to use.” He put me on the right track, although I ended up using getResource(). It works.
STEP 1: Firstly, I got the music to play when I hit run in NetBeans.
STEP 2: I wanted the music to loop (repeat). Eventually I got that right, thanks to the members of StackOverflow. Please see my source code.
STEP 3: Finally I got the mp3 to EMBED in the jar. Now, this is important. At first the music played on my computer, but the jar read it off my hard disc. When I changed the name of the mp3, then the jar crashed, it would not run, it could not find the mp3. I had to embed the mp3 into the jar, put it inside the jar (in the jar) otherwise it would not play on somebody else’s computer. That’s where getResource() did the trick.
STEP 4: Then I emailed my jar to friends. Some service providers don’t trust a jar, they sent the emails back to me, undelivered. Other service providers don’t have a problem and delivered the emails. So, what did I do? I changed the name of the *.jar to *.mp4 and the emails were delivered, I asked my friends to change it back from *.mp4 to *.jar. It worked.
Here is my source code. I’m sure it’s not perfect, but it works, thanks to StackOverflow.
/* Of course, one needs to import the following gizmo’s (and others): */
import javafx.util.Duration;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
/* I want to EMBED the music inside the jar (in the jar).
The secret seems to be getResource. The source code starts here,
to EMBED the sound (DollyParton.mp3) into the jar: */
//************************ begin the music ***********************
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
play();
}
public static void main(String[] args) {
launch(args);
}
MediaPlayer musicplayer; {
/* Put your music file IN THE JAR, "getResourceAsStream()" is
the API you want to use. Put the DollyParton.mp3 into the Windows
folder src/rockymountain. NetBeans automatically copies the mp3
to the folder build/classes/rockymountain. */
Media mp3MusicFile = new Media(getClass().getResource("DollyParton.mp3").toExternalForm());
musicplayer = new MediaPlayer(mp3MusicFile);
musicplayer.setAutoPlay(true);
musicplayer.setVolume(0.9); // from 0 to 1
//***************** loop (repeat) the music ******************
musicplayer.setOnEndOfMedia(new Runnable() {
public void run() {
musicplayer.seek(Duration.ZERO);
}
});
//*************** end of loop (repeat) the music **************
}
//**************************** end of music *************************
I put the mp3 into the Windows folder src/rockymountain. Then NetBeans automatically copied the mp3 to the folder build/classes/rockymountain. NetBeans does not copy the mp3 to the folder /resources, a file that I created unnecessarily, because someone said so. The /resources folder is not needed, it remains empty.
Create a Java ARchive (jar) file using NetBeans as follows:
Right-click on the Project name
Select Properties
Click Packaging
Check Build JAR after Compiling
Check Compress JAR File
Click OK to accept changes
Right-click on the Project name
Select Clean and Build
The JAR file is built. To view it inside NetBeans:
Click the Files tab
Expand ProjectName >> dist (distribution). The jar file is inside the dist folder.
Try to add --add-modules=javafx.controls,javafx.media in your VM options.
I tried this three lines and it worked!
Media sound = new Media(new File("src/music/menu.mp3").toURI().toString());
MediaPlayer player = new MediaPlayer(sound);
player.play();
First you need to put the code in try and catch to catch any error, second you must
define the JFXPanel to define it to the media package and the tool kit ,so this is the code:
package test1;
import java.io.File;
import javafx.scene.media.Media;
import javax.swing.JOptionPane;
import javafx.scene.media.MediaPlayer;
import javafx.embed.swing.JFXPanel;
public static void main(String[] args) {
try {
JFXPanel j = new JFXPanel();
String uriString = new File(""C:\\Users\\Mike\\workspace\\b\\src\\hero.mp3"").toURI().toString();
MediaPlayer Player = new MediaPlayer(new Media(uriString));
Player.play();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
and a good info for you can put only file name
inside the File() exp: String uri = new File("hero.mp3").toURI().toString();
I'm trying to use Javas JFileChooser in my LibGDX scene2d project, but as soon as I launch JFileChooser my program freezes.
Here is the code I use to launch file chooser:
private String getPath(){
String path = "";
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
try {
path = file.getAbsolutePath();
} catch (Exception ex) {
System.out.println("problem accessing file" + file.getAbsolutePath() + "\n" + ex.getMessage());
}
} else {
System.out.println("File access cancelled by user.");
}
return path;
}
is it swing and libgdx compability problem or is there something I am missing? Same code works perfectly with nativa java projects.
Except instead of: fc.showOpenDialog(null);
I use: fc.showOpenDialog(button); // button is the JButton that triggers the event.
any idea what am I doing wrong?
EDIT: I don't really mind if it wont work on other platforms than Windows.
BUT if I choose to go with cross platform solution, and use LibGDX's method, do I have to create file chooser class with UI from scratch all by myself?
Ok based on your comments from the answer above I get a sense that what you are trying to do is invoke a swing window INSIDE your LibGDX game window, which is an open GL rendering scene.
Let me stop you right there. The swing toolkit invokes its own rendering engine, because it's not intended for this purpose at all - it's intended for desktop applications. So when you instantiate the dialogue, all sorts of other oracle java stuff gets instantiated along with it, like the Graphics2D class. You can't just add this class to a scene2D stage and expect that it draws. They don't implement the same interfaces or inherit from the same base classes. The draw(Graphics2D graphics) method that your JFileChooser implements is not the same as whatever draw(SomeClass foo) method that your libGDX classes implement.
So if you want to make a file chooser window, you need to start looking at the libGDX widget libraries. There might be something that someone has put together already, but my approach for my next libGDX project is going to be to extend these classes for my own UI libraries. I don't know what your project is, or what your timeline is like, but it's certainly a better approach then trying to adapt the swing toolkit to render in an OpenGL rendering scene.
edit
After some quick reading, I'm going to go one further and hazard a guess that the way the swing toolkit gets rendered is entirely dependent on the implementation of the JVM for a specific platform. Now this is where my CS knowledge starts to be a little limited, but I would hazard another guess that this is way way different than the LWJGL implementation of OpenGl by way of using Java wrappers for C libraries.
Personally I dislike the existing FileChooser UIs inside LibGDX. So I created a solution which works using the JFileChooser. Here is some quick and dirty code:
new Thread(new Runnable() {
#Override
public void run() {
JFileChooser chooser = new JFileChooser();
JFrame f = new JFrame();
f.setVisible(true);
f.toFront();
f.setVisible(false);
int res = chooser.showSaveDialog(f);
f.dispose();
if (res == JFileChooser.APPROVE_OPTION) {
//Do some stuff
}
}
}).start();
This will open the FileChooser in front of the LibGDX window without blocking the main Thread. Just tested this on Windows 7, 8, 10 and it only works in window mode ofc.
Coming late to the party but if the point of the question is to invoke a "native" ie. non-gdx file chooser from a libgdx project I made a library to do so here: https://github.com/spookygames/gdx-nativefilechooser.
Example from the readme:
// Configure
NativeFileChooserConfiguration conf = new NativeFileChooserConfiguration();
// Starting from user's dir
conf.directory = Gdx.files.absolute(System.getProperty("user.home"));
// Filter out all files which do not have the .ogg extension and are not of an audio MIME type - belt and braces
conf.mimeFilter = "audio/*";
conf.nameFilter = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith("ogg");
}
};
// Add a nice title
conf.title = "Choose audio file";
fileChooser.chooseFile(conf, new NativeFileChooserCallback() {
#Override
public void onFileChosen(FileHandle file) {
// Do stuff with file, yay!
}
#Override
public void onCancellation() {
// Warn user how rude it can be to cancel developer's effort
}
#Override
public void onError(Exception exception) {
// Handle error (hint: use exception type)
}
});
On the desktop, this example will currently launch an AWT FileDialog (not exactly what is asked) yet a Swing version is currently on the master branch and should be incorporated to the next version of the lib.
I have to create an application that will automatically open a powerpoint file, let it play through, and then close it. Not only do I need to figure out HOW to close it, but I also must detect when it closes or stops.
First option:
I know how long each powerpoint will play for, so I can hardcode when to close the file. I just need to know how to do that. There are no methods in the desktop class (that I could find) for closing.
Second option:
If someone knows a microsoft powerpoint api that lets me open powerpoints and use java to progress through the slideshow and get the state or something, that'd be great. I wouldn't have to go into each presentation and count the number of slides and the transition timer on each slide.
The opening, letting it play, and closing it is a small part of the app I need to create. But here is what I have so far with regards to THIS problem:
File myfile = new File("PowerPoint.ppsx");
try {
Desktop.getDesktop().open(myfile);
} catch (IOException ex) {
Logger.getLogger(Sc.class.getName()).log(Level.SEVERE, null, ex);
}
Probably this is the solution how to close external program:
http://www.java-forums.org/new-java/59691-close-another-program.html#post285956
If you want to detect when program has stopped running then you can start new thread with loop which from time to time will check if the program process is still running, using the same method as mentioned in link.
This is solution only for one (Windows) platform, Java is not the best choice for such tasks.
Here a solution using JNA. First we get the handle, we search using the "class name" of the window. You can determine the class name for a specific program (in this case Powerpoint) with a special utility like Spy++ (included with Visual Studio). It's possible to make the search more precise using the class name and the window caption (but here I use only the class name) so if you have more than one presentation running ... you may not close the good one!.
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.platform.win32.WinDef.HWND;
// https://github.com/twall/jna#readme
// you need 2 jars : jna-3.5.1.jar and platform-3.5.1.jar
public class KillMyPP {
public static void main(String[] args) {
HWND hwnd = User32.INSTANCE.FindWindow("screenClass", null);
if (hwnd == null) {
System.out.println("PPSX is not running");
}
else {
User32.INSTANCE.PostMessage(hwnd, WinUser.WM_QUIT, null, null);
}
}
}