I'm trying to play a sound when a button is clicked or when a new view is showing up. I wrote this method to play a sound:
void play_sound(String musicFile) {
AudioClip sound = new AudioClip(new File(musicFile).toURI().toString());
sound.play();
}
and this is how I call it:
String musicFile = "src/resources/sounds/applause.mp3";
play_sound(musicFile);
I have to mention that applause.mp3 is downloaded from the web and when I play a sound from web it works. But when I want to play a sound that is recorded (for example app.mp3), it doesn't work anymore. All these files are in the same folder(sounds).
Your file path should definitely start with a / to mark it as absolute (inside of the jar file).
Then, you should'nt use the File class to load resources from inside the jar file. Use
String path = getClass().getResource("/resources/sounds/applause.mp3")
AudioClip sound = new AudioClip(path);
instead.
Cheers
Related
I'm trying to make a song play when opening the .JAR-file. It works fine in Netbeans but when opening the .Jar-file only the button for scenechange and the images on those scenes show.
In the controller for the FXML i've initialized a Thread for playing the song:
#Override
public void initialize(URL url, ResourceBundle rb) {
PlaySong ps = new PlaySong();
Thread thread = new Thread(ps);
thread.start();
}
This calls the class with the thread which should play the song:
public class PlaySong implements Runnable {
#Override
public void run() {
playSong();
}
static void playSong(){
try{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("/src/maanedsdag2/AssetsLibrary/James Smith - Just the Way You Are.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(clip.getMicrosecondLength()/1000);
} catch(Exception e){
}
}
}
My intent is to start playing the song when opening the FXML via the initialize method.
Hope you guys can help.
Your music file should be inside of the 'src' file of your project for being deployed in JAR. And you should use "getResourceAsStream()" to get your sound file.
When you launch your application from your IDE you can access to src file because your JVM execution Path is your project folder.
So you will understand that in a jar you don't have your project. In a Jar the execution path is the folder containing your jar and you will agree that even manually you don't found the folder src in this folder?
You need to consider your music track as resource and not as a file. I suggest you to read: Location-Independent Access to Resources.
But in your case:
SomeClass.class.getResourceAsStream("relativePathfromSomeClasstoyourwavFile");
Duplicate?
OS file systems do not "see" into jar files. Use a URL instead, which can.
It is common to use a relative addressing scheme, and to place the audio in a resources folder of some sort. But you can also just put the audio in the same file as the class that is calling it. Or reference the root of your project with an "absolute" address (address starts with char "/"). Your choice.
The "duplicate" tag above has code examples.
I am developing a test app that does nothing else than play music. The idea behind this app is that normally you have a music player that takes ages to load and has all those extra gadgets and gizmos that nobody, or at least not you, uses. This app only plays music, period. And it loads almost instantly.
But I got something funny. I need to find a way for the user to select a song from the filesystem, but I haven't got that working yet, so I am using a fixed song URI to play it. When I put this song on the local filesystem(i.e. /storage/emulated/0/Music/SongName.mp3), the app crashes upon pressing the play button. But when I put the song on the SD card(i.e. /storage/extSdCard/Music/SongName.mp3) it works fine.
Well, I got it to work, but I don't know how or why it works. Normally I would be surprised and not touch that piece of code again so that it keeps working, but this time I am learning programming on Android and I want to know why it works.
This is the code for playing from the SD card(works):
p = new MediaPlayer();
p.setAudioStreamType(AudioManager.STREAM_MUSIC);
p.setDataSource(getApplicationContext(), Uri.fromFile(new File("/storage/extSdCard/Tests/Take Back The Night.mp3")));
p.prepare();
p.start();
And this is the code for playing from the local fs(does not work):
p = new MediaPlayer();
p.setAudioStreamType(AudioManager.STREAM_MUSIC);
p.setDataSource(getApplicationContext(), Uri.fromFile(new File("/storage/emulated/0/Music/heybrother.mp3")));
p.prepare();
p.start();
As you can see, it's pretty much the same, so I concluded that there is probably something wrong in the URI. But I can't see any typos, and I retyped it multiple times. Is the URI malformed for this purpose?
I got it working!
First, you need to get the path of the music folder like this:
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
.getPath() + "/";
Then you can append the file name in the music folder:
String file = path + "ThatOneSong.mp3";
And then play it as normal. (Or you could do this in one long line but that's kind of cluttered.)
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 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.
Is this even possible? I have tried using the MediaPlayer but it throws a NullPointerException on the MediaPlayer object. I can get audio to work but video wont.
mp=MediaPlayer.create(getApplicationContext(), R.raw.sample);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener()
{
public void onCompletion(MediaPlayer mp) {
mp.release();
playing = false;
}
});
the sample is of .mp4 type.
Anyone have an idea of why this is happening or have a suggestion for another method of getting videos to be played?
You can use the following code
VideoView videoView;
VideoView = (VideoView) findViewById (R.id.txt1);
videoView.setVideoPath(path);
videoView.setVisibility(VideoView.VISIBLE);
videoView.start();
i have tried to play mp4 on my emulator but it was not showing video but when i tried on device it work fine.
Haven't tried that before but I think you can use vlcj framework that's totally free and can play effectively almost any type of video (and of course plays .mp4 video files) .I can't give you any code in android because have never worked with android but I know java and and it just works.So here what i use in Java:
NativeLibrary.addSearchPath("libvlc",path); //To set path of libvlc
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);//To import libvlc
//The path can be a folder in your android project.All the files needed are in vlc player installation folder.so yes you have to install vlc in your computer to get those files but just once.
canvas = new WindowsCanvas();
panel.add(canvas);//panel is like your VideoView
canvas.setVisible(true);
canvas.setBackground(Color.black);
mediaPlayerFactory = new MediaPlayerFactory();
player12 = mediaPlayerFactory.newEmbeddedMediaPlayer();
CanvasVideoSurface videoSurface = mediaPlayerFactory.newVideoSurface(canvas);
player12.setVideoSurface(videoSurface);
player12.setPlaySubItems(true);
player12.startMedia(yourVideoPath);
player12.setAspectRatio(""+panel.getWidth()+":"+panel.getHeight()); //Those two lines are for your video to be adusted in your panel or better to your VideoView
player12.setCropGeometry(""+panel.getWidth()+":"+panel.getHeight());
The jar files you have to include in your classpath are jna-3.4.0.jar,platform-3.4.0.jar,vlcj-2.1.0.jar