I am trying to play a video file using JMF but it gives me No Media Player found exception.
Here is my code, can anyone tell me what I am doing wrong here?
public class MediaPanel extends JPanel {
public MediaPanel(URL mediaURL) {
setLayout(new BorderLayout());
try {
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
Player mediaPlayer = Manager.createRealizedPlayer(mediaURL);
Component video = mediaPlayer.getVisualComponent();
Component controls = mediaPlayer.getControlPanelComponent();
if (video != null)
add(video, BorderLayout.CENTER);
if (controls != null)
add(controls, BorderLayout.SOUTH);
mediaPlayer.start();
} catch (NoPlayerException noPlayerException) {
System.err.println("No media player found");
} // end catch
catch (CannotRealizeException cannotRealizeException) {
System.err.println("Could not realize media player");
} // end catch
catch (IOException iOException) {
System.err.println("Error reading from the source");
}
}
}
public class MediaTest {
public static void main(String args[]) {
// create a file chooser
JFileChooser fileChooser = new JFileChooser();
// show open file dialog
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) // user chose a file
{
URL mediaURL = null;
Player mediaPlayer = null;
try {
// get the file as URL
mediaURL = fileChooser.getSelectedFile().toURL();
} catch (MalformedURLException malformedURLException) {
System.err.println("Could not create URL for the file");
}
if (mediaURL != null) {
JFrame mediaTest = new JFrame("Media Tester");
mediaTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MediaPanel mediaPanel = new MediaPanel(mediaURL);
mediaTest.add(mediaPanel);
mediaTest.setSize(300, 300);
mediaTest.setVisible(true);
}
}
}
}
The exception that I am getting is No media player found
What kind of video are you trying to play? JMF is a pretty old library and won't be able to play most of modern video formats, only a few old ones (i am not even sure which ones).
Actually, if I am right, to play something specific you will have to write/add your own video-encoders into JMF or at least download and use existing ones, which are usually outdated.
If you really want to have something like tunable video player that could play any modern video there are two options (in my opinion):
Use vlcj library to embed VLC video player into your Java-application
USe JavaFX media player
I am offering only those two because I have dig through tons of libraries some time ago and there were nothing else even close to these two. Plus most of other libraries are outdated as well as JMF itself and these two are getting frequent updates and are supported with lots of users so those two are the best choice.
In case you don't mind embedding Java FX player into your application - that might be your choice.
On the other hand - vlcj is stable and easily integrated into Swing applications (its not like its hard with Java FX, but vlcj might be better for some cases).
Anyway, it is your call what to choose.
Related
I'm developing a stream video app in Android with MediaPlayer. The problem is that I need to show the current bitrate, but I haven't found any valid suggestions on how to do get it?
Here is how I'm setting the video url to play:
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(VIDEO_PATH);
mediaPlayer.prepare();
mediaPlayer.init();
} catch (IOException e) {
e.printStackTrace();
}
I don't know if the only way to get that working is using ExoPlayer (which I've read it may be possible)
Any suggestions?
Thanks!
Apparently you cannot do this with MediaPlayer but you can use MediaMetadataRetriever, which is available since API level 10, i.e., quite a while ago.
int getBitRate(String url) {
final MediaMetadataRetriever mmr = new MediaMetadataRetriever();
try {
mmr.setDataSource(url, Collections.EMPTY_MAP);
return Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
} catch (NumberFormatException e) {
return 0;
} finally {
mmr.release();
}
}
The disadvantage this can have is that you will make an extra HTTP request for getting the metadata (only an RTT if you are streaming from an URI; if you are reading from an file descriptor it could be more serious). Hopefully no big deal.
I working on a program that both plays a sound when you click a button in an applet and in an application but I keep receiving an error while in the application portion of the program.
This is the error I get: sample.mp3 (The system cannot find the file specified)
but I clearly have it in my project.
public class project extends JApplet {
public void init() {
add(new AppletOrApplicationMainComponent());
}
public static void main(String args[]) {
JFrame frame = new JFrame("");
frame.getContentPane().add(new AppletOrApplicationMainComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class AppletOrApplicationMainComponent extends JPanel {
public AppletOrApplicationMainComponent() {
super(new BorderLayout());
JButton button = new JButton("Play");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Play();
}
});
add(button, BorderLayout.SOUTH);
}
private void Play(){
try{
File file = new File("sample.mp3");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
Player player = new Player(bis);
player.play();
}catch(Exception e){
e.printStackTrace();
}
}
}
In all that excitement, almost forgot to answer the question:
How do I play an mp3 file for both an application and applet?
Firstly, using URL to access a resource is compatible with both applet and application. The URL can be obtained from Class.getResource(String). For more details on using the method, see the embedded resource info. page.
As to playing an MP3 for which we have an URL, see the MP3 decoding support section of the Java Sound info. page. Basically it boils down to adding an MP3 SPI to the run-time class-path of the app.
Also note that the Clip convenience class mentioned in that page (and shown in the example) does not work with large files. From memory, it will hold at most 1 second of CD quality (stereophonic, 16 bit, 44.1 KHz) sound. For larger files you might use an AudioInputStream directly, reading the bytes and feeding them back out to the sound API that plays them. Either that or use BigClip, which caches the entire stream bytes in memory, much like Clip.
I'm using OpenCV for a object detection project. I'm trying to read frames from a stored video file using VideoCapture, but in OpenCV Java there is no current implementation. I followed instructions in this post: open video file with opencv java, to edit the source files of OpenCV Java to allow this functionality. The problem is I don't know how to recompile the files? - since I just added the downloaded opencv jar file into my eclipse project originally.
You should probably try JavaCV, an OpenCV wrapper for Java.
This post shows what you need to download/install to get things working on your system, but I'm sure you can find more updated posts around the Web.
One of the demos I present during my OpenCV mini-courses contains a source code that uses JavaCV to load a video file and display it on a window:
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.FrameGrabber;
public class OpenCV_tut4
{
public static void main(String[] args)
{
FrameGrabber grabber = new OpenCVFrameGrabber("demo.avi");
if (grabber == null)
{
System.out.println("!!! Failed OpenCVFrameGrabber");
return;
}
cvNamedWindow("video_demo");
try
{
grabber.start(); // initialize video capture
IplImage frame = null;
while (true)
{
frame = grabber.grab(); // capture a single frame
if (frame == null)
{
System.out.println("!!! Failed grab");
break;
}
cvShowImage("video_demo", frame);
int key = cvWaitKey(33);
if (key == 27) // ESC was pressed, abort!
break;
}
}
catch (Exception e)
{
System.out.println("!!! An exception occurred");
}
}
}
I've been trying to deal with sound on my Applet for a bit now, and Instead of trying all the different methods, what is the best way to play Sound in Java? There are a few requirements:
Needs to be able to loop
Needs to be able to load a WAV from an archive JAR(I think with the getClass().getResource)
Needs to be able to play more than one sound at the same time, and not clip already playing sounds
Thanks you so much for looking at my question and I hope you guys have an answer!
Thanks to the wonderful help I almost have it working with this:
public class MyGame() {
Clip bullet;
public void init(){
try {
bullet = AudioSystem.getClip();
URL url2 = this.getClass().getResource("bulletSound.wav");
AudioInputStream ais2 = AudioSystem.getAudioInputStream( url2 );
bullet.open(ais2);
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
randomMethodToPlayBullet(){
bullet.setFramePosition(0);
bullet.start();
}
}
The problem is that the bullet sound plays, but if the randomMethodToPlayBullet is called say twice in a row, before the first bullet sound is done, the seonc one doesnt play.
The best way to load resources from jar file is to put in the same folder a class and get the resource with .class.getResource(...) or .class.getResourceaAsStream(...) methods:
URL url = ClazzInTheFolderOfMyMidiFile.class.getResource(nameOfMidiFile);
or
InputStream resourceAsStream = ClazzInTheFolderOfMyMidiFile.class.getResourceAsStream(nameOfMidiFile);
The answer for:
Small samples is Clip. See the Java Sound info. page for an example of use.
Large samples is BigClip.
You can't play the same Clip twice at the same time. You have to create another instance of Clip to play the sound twice at the same time.
Note that there will be a limit how many clips you can play, so the clip API may not be suited to support a sound-heavy game.
I am developing an image editing app, so want to display an image selected by JFileChooser, so what would be best approach so that it can display all formats jpg, png, gif etc. OpenButton is used for invocation of filechooser.
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChosser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChosser.getSelectedFile();
// What to do with the file
// I want code for this part
try {
//code that might create an exception
}
catch (Exception e1) {
e.printStackTrace();
}
}
}
The easiest way is probably to create an ImageIcon from the URL of the file (or from the content of the file as bytes, or from the file name), and to wrap this ImageIcon into a JLabel:
iconLabel.setIcon(new ImageIcon(file.toURI().toURL()));
But if your app is supposed to edit the image, then you'll have to learn how to manipulate java.awt.Image instances, and the easiest way won't be sufficient.