JMF provides a class MediaPlayer
which can be used as a full-featured player. However, I can't find a way to play an audio file. Some snippets of the code used.
import javax.media.bean.playerbean.MediaPlayer;
// ....
MediaPlayer mp = new MediaPlayer();
mp.setMediaLocation(location of file); // <- syntax error!
mp.start();
But it doesn't work. Eclipse shows this error:
Syntax error on token "setMediaLocation", Identifier expected after this token
..on setMediaLocation()
method.
Can someone tell me how to use MediaPlayer
class to play audio file? and what is wrong in my coding?
You do not literally have ..setMediaLocation(location of file);
in the source do you? I thought that was paraphrased.
In that case, the answer is to supply an argument to the setMediaLocation()
method. The docs. specify a String
or MediaLocator
instance.
I avoid using String
instances to represent file or URL based sources. If a method needs a File
or URL
- give it a File
or URL
. That leaves the best option as a MediaLocator(URL)
. Here is how it might go. First we need a URL
- there are a number of different ways of getting one, depending on what the source of the URL is. E.G. the internet, a file on the local file-system, or an embedded resource in a Jar delivered with the app. The last two might be something like:
File based URL
File mediaFile = new File("user.mp3");
URL mediaURL = mediaFile.toURI().toURL();
// ...
Embedded resource URL
URL mediaURL = this.getClass().getResource("/path/to/our.mp3");
// ...
Once there is a mediaURL
instance, we can create a locator and use it in the method.
Using the URL
MediaLocator mediaLocator = new MediaLocator(mediaURL);
MediaPlayer mp = new MediaPlayer();
mp.setMediaLocation(mediaLocator);
// ...
General tips
- JMF is an abandoned API.
- Since you seem interested only in audio, look to use Java Sound. It can play audio samples just fine, is part of core Java, and with a small part of the JMF, can play MP3 format (see link for details).
- You seem new to the abandoned API being used, Eclipse and debugging. Perhaps you should focus on simpler things for the moment. Media handling is an advanced topic.