Can anyone please tell me which is the best way to play video in a JPanel.I am currently working on a learning software for children where some learning videos will be played upon selection.Videos are stored in some folder.I have successfully done the job using JMF but the problem is its kinda slow.It takes some time to start the video, though the videos are not too large(2-4 MB).What can i do to make it quick-start,
Thank u
public class MediaPanel extends JPanel
{
public static boolean playing = false;
public static Player mediaPlayer;
public MediaPanel( URL mediaURL )
{
setLayout( new BorderLayout() ); // use a BorderLayout
// Use lightweight components for Swing compatibility
//Component controls = mediaPlayer.getControlPanelComponent();
} // end MediaPanel constructor
public void play(URL mediaURL) throws NoPlayerException, CannotRealizeException, IOException, IncompatibleSourceException{
Manager.setHint( Manager.LIGHTWEIGHT_RENDERER, true );
System.out.println("sdfdsg");
mediaPlayer = Manager.createRealizedPlayer( mediaURL );
Component video = mediaPlayer.getVisualComponent();
if ( video != null )
add( video);
mediaPlayer.start();
playing=true;
}
public void stop(){
mediaPlayer.stop();
playing = false;
}
public void play_one(){
mediaPlayer.stop();
mediaPlayer.start();
}
}
public class MediaPanel extends JPanel
{
public static boolean playing = false;
public static Player mediaPlayer;
public MediaPanel( URL mediaURL )
{
setLayout( new BorderLayout() );
} // end MediaPanel constructor
public void play(URL mediaURL) throws NoPlayerException, CannotRealizeException, IOException, IncompatibleSourceException{
Manager.setHint( Manager.LIGHTWEIGHT_RENDERER, true );
mediaPlayer = Manager.createRealizedPlayer( mediaURL );
Component video = mediaPlayer.getVisualComponent();
if ( video != null )
add( video);
mediaPlayer.start();
playing=true;
}
public void stop(){
mediaPlayer.stop();
playing = false;
}
public void play_one(){
mediaPlayer.stop();
mediaPlayer.start();
}
}
and the portion of the source code where i used this class..
try {
Home.text.setText("wait..");
if(Home.mediaPanel.playing==true)
Home.mediaPanel.stop();
Home.mediaPanel.play(new URL("file://C://Users//zubair//workspace//learningKit//"+Home.selected_topic+"//"+Home.sele cted_group+"//v"+k+".flv"));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JMF is from the stone-age. Do you have any reasons to stick to it?
I would recommend using JavaFX which has media support including video playing. JavaFX is part of Java 8, and is also shipped with Java 7 (just not on the default classpath). You can play a supported video format (*.flv, *.mp4) with just a few lines of code, and it also uses hardware acceleration if available.
Basically you only need to create a Media, a MediaPlayer and a MediaView class:
Media m = new Media(Paths.get("example.flv").toURI().toString());
MediaPlayer mp = new MediaPlayer(m);
MediaView mv = new MediaView(mp);
// Add the mediaview component somewhere to your GUI
// And you're done. You can start playing the video by:
mp.play();
Here is a short, complete example application which plays a video:
http://www.java2s.com/Code/Java/JavaFX/FullScreenVideoPlayer.htm
Official Oracle tutorial:
Introduction to JavaFX Media
Related
I know, there are several posts handling with this problem here on Stackoverflow, but I didnĀ“t get a solution for my problem. I have an ipcam and I want to capture the livestream using java. The problem is, that I can only access the cam via RTSP. There is no normal http://xxx.xxx.xxx:xx access.
I use the OpenCv library but unfortunately my program only works with the webcam of my laptop because it is the default device.
protected void init()
{
this.capture = new VideoCapture();
this.faceCascade = new CascadeClassifier();
this.absoluteFaceSize = 0;
}
/**
* The action triggered by pushing the button on the GUI
*/
#FXML
protected void startCamera()
{
// set a fixed width for the frame
originalFrame.setFitWidth(600);
// preserve image ratio
originalFrame.setPreserveRatio(true);
if (!this.cameraActive)
{
// disable setting checkboxes
this.haarClassifier.setDisable(true);
this.lbpClassifier.setDisable(true);
// start the video capture
//String URLName = "rtsp://username:password#rtsp:554/h264/ch1/main/av_stream";
this.capture.open("rtsp://192.168.178.161:554/onvif1");
// is the video stream available?
if (this.capture.isOpened())
{
this.cameraActive = true;
// grab a frame every 33 ms (30 frames/sec)
Runnable frameGrabber = new Runnable() {
#Override
public void run()
{
Image imageToShow = grabFrame();
originalFrame.setImage(imageToShow);
}
};
this.timer = Executors.newSingleThreadScheduledExecutor();
this.timer.scheduleAtFixedRate(frameGrabber, 0, 33, TimeUnit.MILLISECONDS);
// update the button content
this.cameraButton.setText("Stop Camera");
}
else
{
// log the error
System.err.println("Failed to open the camera connection...");
}
}
I'm using VLCJ for playing mp4 video in my swing application. It can play properly but when I pause() the video followed by a play() it cannot display video but it is able to resume audio. If I call stop() instead of pause() everything works fine but it starts playing from the beginning. How can I pause the video properly so that I can resume the video?
I was trying with the following class:
public class JVLCPlayerPanel extends javax.swing.JPanel
{
private File vlcPath = new File("C:\\Program Files\\VideoLAN\\VLC");
private EmbeddedMediaPlayer player;
public JVLCPlayerPanel() {
initComponents();
NativeLibrary.addSearchPath("libvlc", vlcPath.getAbsolutePath());
EmbeddedMediaPlayerComponent videoCanvas = new EmbeddedMediaPlayerComponent();
this.setLayout(new BorderLayout());
this.add(videoCanvas, BorderLayout.CENTER);
this.player = videoCanvas.getMediaPlayer();
this.player.setPause(true);
}
public void play(String media)
{
player.prepareMedia(media);
player.parseMedia();
player.play();
}
public void pause()
{
player.pause();
}
public void resume()
{
player.play();
}
}
try using this code use pause() method of MediaPlayer
and use same pause() method to play it works for me
pauseButton.addActionListener((ActionEvent e) -> {
mediaPlayerComponent.getMediaPlayer().pause();
});
According to your post and comments, you are trying to switch a single media player component between multiple panels.
This simply does not work.
With vlcj/LibVLC the component that hosts the video surface must be "displayable" and must remain so at all times. You can not "re-parent" the video surface to another component, you can not even hide the component (you can set it to 1x1, or the best solution is to use a CardLayout, to hide it).
The reason it works when you first stop then play is that in this case vlcj will "re-associate" the video surface with the native media player. This can not be done while the video is playing. There's nothing you can do about it.
Probably keeping one media player per panel, and using a CardLayout, is the best solution.
I am a beginner in java programming language, Recently I have got a work to capture frames from a video file, I have also developed a program that does so, but it does that when the video is played on screen with the help of any player.
I have developed following program to do so.
public class Beginning implements Runnable {
private Thread thread;
private static long counter = 0;
private final int FRAME_CAPTURE_RATE = 124;
private Robot robot;
public Beginning() throws Exception {
robot = new Robot();
thread = new Thread(this);
thread.start();
}
public static void main(String[] args) throws Exception {
Beginning beginning = new Beginning();
}
public void run() {
for (;;) {
try {
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = robot.createScreenCapture(screenRect);
ImageIO.write(bufferedImage, "png", new File("D:\\CapturedFrame\\toolImage" + counter + ".png"));
counter++;
thread.sleep(FRAME_CAPTURE_RATE);
} catch (Exception e) {
System.err.println("Something fishy is going on...");
}
}
}
}
My sir has told to capture all frames from any specified videos without playing it on screen, Can anyone please suggest me that how can I do so.
Well, you can simply use OpenCV. Here is an example of it.
https://www.tutorialspoint.com/opencv/opencv_using_camera.htm
You can use any video in place of the camera in the VideoCapture class as:
VideoCapture capture = new VideoCapture(0);
instead of the above line of code, you can use
VideoCapture capture = new VideoCapture("/location/of/video/");
I hope this is what you are looking for.
I'm working at an Audio Player, which is written in Java with GUI. For playing the mp3 files, I've chosen JLayer library from javazoom because I saw it's very popular and used. I made the GUI, managed to play the selected mp3 file from the playlist.
My problem is that if I press many times on the play button or on the file from the playlist it will start playing the song as many times as I press it and I want to play it one the same thread ; if I press again play button I want to play again not to start the same song while the current one is playing .
Here is my code which play the mp3 file:
public class Playing implements Runnable{
private Player mp3Player;
private Thread playerThread;
public void createPlayer(FileInputStream file) throws JavaLayerException{
mp3Player = new Player(file);
playerThread = new Thread(this);
playerThread.start();
}
#Override
public void run(){
try {
mp3Player.play();
}
catch (JavaLayerException ex) {
Logger.getLogger(Playing.class.getName()).log(Level.SEVERE, null, ex);
}
}
This is my method for the play button:
public void createPlayButton(){
play = new JButton();
playButton = new ImageIcon("D:/Audio Player/Images/playButton.png");
play.setBounds(125, 100, 50, 50);
play.setIcon(playButton);
play.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < select.getFilesPath().size(); i++){
if (select.getFilesPath().get(i).toString().contains(playlistBody.getSongName())){
try {
mp3Player.createPlayer(new FileInputStream(new File(select.getFilesPath().get(i).toString())));
} catch (JavaLayerException ex) {
Logger.getLogger(PlayerBody.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(PlayerBody.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
});
}
I mention that I'm new to multithreading, so dont be so hard on me. If I cannot do this with JLayer, please recommend me a good library with which I can play mp3 files. Thank you in advance and I'm waiting for your suggestions.
I fixed my issue with the threads; I'll put the solution, maybe will help someone.
static int fileRunning = 0;
public void playMp3(FileInputStream file) throws JavaLayerException{
if (fileRunning == 0){
mp3Player = new Player(file);
playerThread = new Thread(this);
playerThread.start();
fileRunning = 1;
}
}
So the main idea is that when I start playing a song, that int will take value 1, and it won't be 0, so no more threads can be made.
use this after you press you play button and the thread has been started once player start the button will disable and let it enable again once the song is being completed
yourplaybutton.setEnabled(false);
I can play .mpg format video with the Java media framework.
But I can not play all format of video.
When I want to play .AVI format video, the video is play but the sound is not come.
How to play other format such as FLV, mp4, avi?
public class MediaPanel extends JPanel
{
public Player mediaPlayer;
public Component video;
public Component controls;
public MediaPanel(URL mediaURl)
{
setLayout(new BorderLayout());
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
try
{
//Player
// this. mediaPlayer.stop();
//this.mediaPlayer.close();
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");
}
catch(CannotRealizeException cannotRealizeException)
{
System.err.println("Could not");
}
catch(IOException iOException)
{
System.err.println("Error");
}
}}
You need to add a Service Provider Interface for the encoding in question. E.G. The JMF provides an SPI for MP3 that can be added to the run-time class-path of an app. to allow it to read MP3s using Java Sound.