I am using vlcj on my java program. I need the video to play repeatedly. I've used setRepeat(true); but it doesn't work for me. Is this any other to loop the video? Or am I doing it wrong? Please help me. Thanks a lot.
public QueueMonitor() {
initComponents();
//VIDEO
chargerLibrairie();
Canvas c = new Canvas();
panel.add(c);
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
//Create a media player instance
EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(c));
mediaPlayer.playMedia("Ospital1.mp4");
mediaPlayer.setRepeat(true);
mediaPlayer.setPlaySubItems(true);
}
public static void chargerLibrairie(){
NativeLibrary.addSearchPath(
RuntimeUtil.getLibVlcLibraryName(), "C:/Program Files/VideoLAN/VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
LibXUtil.initialise();
}
Also, how can I put some functions like pause, play, lower volume while the program is running? Like how a normal video player is able to do.
Here are some minimal examples of how to get repeat play working with vlcj.
For current versions of vlcj, 4.x and later:
// vlcj 4.x+
public class RepeatPlayer {
public static void main(String[] args) throws Exception {
String mrl = "some-cool-video.mp3";
EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
JFrame f = new JFrame("Repeat Player");
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
}
});
f.setContentPane(mediaPlayerComponent);
f.setVisible(true);
mediaPlayerComponent.mediaPlayer().controls().setRepeat(true);
mediaPlayerComponent.mediaPlayer().media().play(mrl);
Thread.currentThread().join();
}
}
Since it looks like you're using an ancient version of vlcj, this is how it was done previously:
// vlcj 3.12.1
public class RepeatPlayer {
public static void main(String[] args) throws Exception {
String mrl = "some-cool-video.mp3";
final EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
JFrame f = new JFrame("Repeat Player");
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
}
});
f.setContentPane(mediaPlayerComponent);
f.setVisible(true);
mediaPlayerComponent.getMediaPlayer().setRepeat(true);
mediaPlayerComponent.getMediaPlayer().playMedia(mrl);
Thread.currentThread().join();
}
}
The code in the original question was therefore broadly correct at least with regards to the repeat-play functionality. The most likely problem with the original code is that the media player was garbage collected due to a failure to hold the object references.
public class Video extends javax.swing.JPanel
{
private EmbeddedMediaPlayerComponent video;
private EmbeddedMediaPlayer mediaPlayer;
public Video()
{
initComponents();
initVideo();
}
private void initVideo()
{
video = new EmbeddedMediaPlayerComponent()
{
#Override
public void finished(MediaPlayer mediaPlayer)
{
super.finished(mediaPlayer);
System.out.println("FINISHED");
new Thread(() -> {
System.gc();
mediaPlayer.controls().setTime(0);
mediaPlayer.controls().play();
}).start();
}
};
mediaPlayer = video.mediaPlayer();
mediaPlayer.input().enableKeyInputHandling(false);
mediaPlayer.input().enableMouseInputHandling(false);
add(video, BorderLayout.CENTER);
}
public void start(String path)
{
mediaPlayer.media().prepare(path);
mediaPlayer.controls().play();
}
public void stop()
{
mediaPlayer.controls().stop();
mediaPlayer.release();
video.release();
}
#SuppressWarnings("unchecked")
private void initComponents()
{
setLayout(new java.awt.BorderLayout());
}
}
Related
Methods are underlined in red. I have tried to figure out why this is happening, but I keep running into cannot resolve method. I have the methods in the main TextoToSpeechExample1 class and am invoking the methods in my gui class.
class TextToSpeechExample1 {
public static void main(String args[]) throws IOException, EngineException, AudioException, InterruptedException {
static void start(){
// code to be executed
String fileName = "/Users/stevenshivayka/Documents/kjv.txt";
Path path = Paths.get(fileName);
byte[] bytes = Files.readAllBytes(path);
List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
//setting properties as Kevin Dictionary
System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us" + ".cmu_us_kal.KevinVoiceDirectory");
//registering speech engine
Central.registerEngineCentral("com.sun.speech.freetts" + ".jsapi.FreeTTSEngineCentral");
//create a Synthesizer that generates voice
Synthesizer synthesizer = Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));
//allocates a synthesizer
synthesizer.allocate();
//resume a Synthesizer
synthesizer.resume();
//speak the specified text until the QUEUE become empty
synthesizer.speakPlainText(allLines.toString(), null);
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
//deallocating the Synthesizer
synthesizer.deallocate();
}
public static void pause(){
Synthesizer synthesizer = Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));
synthesizer.allocate();
synthesizer.resume();
synthesizer.deallocate();
synthesizer.pause();
}
}
}
class gui {
public static void main(String args[]) {
JFrame frame = new JFrame("Babbel Audio Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new FlowLayout());
JButton button = new JButton("Start Audio");
frame.add(button); // Adds Button to content pane of frame
frame.setVisible(true);
JButton button2 = new JButton("Pause Audio");
frame.add(button2);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//your actions
TextToSpeechExample1.start();
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//your actions
pause();
}
});
}
}
`
I expected the methods to be invoked. Please if you can review this and see what I am doing wrong I would greatly appreciate it. This is a project I am working on myself.
This isn't a good question for StackOverflow but anyway...
As far as I can see it, you implemented the two methodes start and pause in the main methode but you need to implement them outside of it.
Try this:
class TextToSpeechExample1 {
public static void main(String args[]) throws IOException, EngineException, AudioException, InterruptedException {}
static void start(){
// code to be executed
String fileName = "/Users/stevenshivayka/Documents/kjv.txt";
Path path = Paths.get(fileName);
byte[] bytes = Files.readAllBytes(path);
List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
//setting properties as Kevin Dictionary
System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us" + ".cmu_us_kal.KevinVoiceDirectory");
//registering speech engine
Central.registerEngineCentral("com.sun.speech.freetts" + ".jsapi.FreeTTSEngineCentral");
//create a Synthesizer that generates voice
Synthesizer synthesizer = Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));
//allocates a synthesizer
synthesizer.allocate();
//resume a Synthesizer
synthesizer.resume();
//speak the specified text until the QUEUE become empty
synthesizer.speakPlainText(allLines.toString(), null);
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
//deallocating the Synthesizer
synthesizer.deallocate();
}
public static void pause(){
Synthesizer synthesizer = Central.createSynthesizer(new SynthesizerModeDesc(Locale.US));
synthesizer.allocate();
synthesizer.resume();
synthesizer.deallocate();
synthesizer.pause();
}
}
class gui {
public static void main(String args[]) {
JFrame frame = new JFrame("Babbel Audio Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new FlowLayout());
JButton button = new JButton("Start Audio");
frame.add(button); // Adds Button to content pane of frame
frame.setVisible(true);
JButton button2 = new JButton("Pause Audio");
frame.add(button2);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//your actions
TextToSpeechExample1.start();
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//your actions
TextToSpeechExample1.pause();
}
});
}
}
Quickly looking over your code, a few things jump out:
You're attempting to declare a new function static void start() inside your public static void main(..) function. This isn't allowed in java. You should be declaring your functions inside the class itself:
class TextToSpeechExample1 {
static void start() { ...your code here... }
public static void pause() { ... your code here ... }
public static void main (String args[]) { ... your code here ...}
}
You should probably also look into the basics of access modifiers/specifiers in Java.
You won't be able to call a private function, or a function declared in a private class from another class, for example.
The void start and pause are inside the main void of your TextoToSpeechExample1 class, remove them from inside the main void and it will not give an error.
I need get some data from "Board" Component but i dont know how. I tried Frame.Component.data but is doesn't work.
Code:
public class window extends JFrame {
public window() {
add(new Board());
setResizable(true);
pack();
setTitle("Game");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame ex = new window();
ex.setVisible(true);
ex.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
//ex.Board.data
System.exit(0);
}
});
});
}}
First a little tip to have a quick answer : reduced your code at the minimun to reproduced your bug its easier to understand especially in your case where your real purpose is in a comment ... and then make it compilable ...
To answer to your issue : personnaly i use dedicated fields to have a direct link to object i want to handle later there is two reason first a field is easy to use and don't use lot of memory . Second this solution will not depend on the way your frame is organised. an other way to get the same result is the second snippet the probelme is that if you change your frame organisation you will have to modify your listener
package so1;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Window extends JFrame {
private static final long serialVersionUID = 3000003489937872937L;
public class Data {
public void doSomethings() {
System.out.println("toto");
}
}
public class Board extends JLabel {
private static final long serialVersionUID = 7362684018638848838L;
private Data data = new Data();
}
private Board board;
public Window() {
board = new Board();
add(board);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
Window ex = new Window();
ex.setVisible(true);
ex.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
ex.board.data.doSomethings();
}
});
}
}
the bad solution :
public static void main(String[] args) {
Window ex = new Window();
ex.setVisible(true);
ex.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
((Board)((JPanel)((JLayeredPane)((JRootPane)ex.getComponents()[0]).getComponents()[1]).getComponents()[0]).getComponents()[0]).data.doSomethings();;
}
});
}
I am an absolute beginner in coding. I would like to know why is my Jframe blank when run, how do I fix it. From what I have research on the internet it seems that I should put the component inside the JFrame as it is empty but how do I do it
My Code
public class Video extends JFrame
{
public static void main(String[] args) throws URISyntaxException {
final URI uri = new URI("https://www.youtube.com/watch?v=rl0YiZjTqpw");
class OpenUrlAction implements ActionListener
{
#Override public void actionPerformed(ActionEvent e) {
open(uri);
}
}
JFrame frame = new JFrame("Links");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(410, 400);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JButton btnclickHereTo = new JButton();
btnclickHereTo.setText("<HTML> <FONT color=\"#000099\"><U>Click Here To Watch Video</U></FONT>");
btnclickHereTo.setHorizontalAlignment(SwingConstants.LEFT);
btnclickHereTo.setBorderPainted(false);
btnclickHereTo.setOpaque(false);
btnclickHereTo.setBackground(Color.WHITE);
btnclickHereTo.setToolTipText(uri.toString());
btnclickHereTo.addActionListener(new OpenUrlAction());
container.add(btnclickHereTo);
frame.setVisible(true);
}
private static void open(URI uri)
{
if (Desktop.isDesktopSupported())
{
try
{
Desktop.getDesktop().browse(uri);
}
catch (IOException e)
{ /* TODO: error handling */ }
}
else
{ /* TODO: error handling */ }
}
}
public void setVisible(boolean b) {
Why would you override the setVisible(...) method of your frame? There is no reason to do that.
I am an absolute beginner in coding
Start with something basic, like the example from the Swing tutorial on How to Make Frames.
Keep a reference to the tutorial link handy since it contains information and examples for all Swing basics.
I want to initialize a Graphical User Interface (GUI) for the user to input a form. After this is accomplished i want to open a new GUI, but as soon as the first GUI pops-up the next one is initialized to.
Is there any way to solve this without using waits and notifies?
here is an example of my code:
public static void main(String[] args) {
new GUIForm();
// wait until the user inputs the complete form
new GUIWelcome();
}
It is really simple I woild like to keep it that way.
Create an Interface OnActionListener
public interface OnActionListener {
public void onAction();
}
Add these code in GUIForm class
private OnActionListener listener;
private JButton action;
public GUIForm(OnActionListener listener) {
this.listener = listener;
action = new JButton("Action");
action.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
GUIForm.this.listener.onAction();
}
});
}
Now you can achieve that
new GUIForm(new OnActionListener() {
#Override
public void onAction() {
new GUIWelcome();
}
});
You need to use some sort pub/sub mechanism. This in a nutshell is what you need:
public class PubSub {
public static void main(String[] args) {
JFrame frame1 = new JFrame("GUIForm");
frame1.setSize(640, 480);
JButton button = new JButton("User Input");
JFrame frame2 = new JFrame("Welcome");
frame2.setSize(320, 240);
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
button.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public void mouseExited(MouseEvent e) {
button.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mouseClicked(MouseEvent e) {
frame2.setVisible(true);
}
});
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(button);
frame1.setVisible(true);
}
}
This version uses JFrame's listeners, but you could implement your on callback mechanism to accomplish the same
How can i exit only they new MainGame that i created from Main?
Where Main is having an original layer of game. And the MainGame was a dialog window (such as modal windows).
Main.java: (main code)
public class Main extends JWindow
{
private static JWindow j;
public static MainGame mp;
public static void main(String[] args)
{
new Thread(new Runnable()
{
public void run()
{
mp = new MainGame();
mp.runit();
//mp.stopit();
}
}).start();
j = new Main();
j.setVisible(true);
}
}
MainGame.java: (this was extended by Main, and i would like to quite this only).
public class MainGame extends JWindow
{
private static JWindow j;
public MainGame()
{
// some GUI ...
}
public static void runit()
{
j = new MainGame();
j.setVisible();
}
}
1) better would be implements CardLayout, as create Top-Level Container for new Window, then you'll only to switch betweens Cards
2) don't create lots of Top-Level Container on Runtime, because there are still in JVM memory untill current instance exist,
create required number of and re-use that, to avoiding possible memory lacks
then you have to call setVisible(false) and setVisible(true)
JWindow missed methods for setting setDefaultCloseOperation(Whatever);
3) if you'll create constructor public JWindow(Frame owner), then you'll call directly
SwingUtilities.getAccessibleChildrenCount() and SwingUtilities.getWindowAncestor()
import javax.swing.*;
import java.awt.*;
public class Testing {
private JFrame f = new JFrame("Main Frame");
private JWindow splashScreen = new JWindow();
public Testing() {
splashScreen = new JWindow(f);
splashScreen.getContentPane().setLayout(new GridBagLayout());
JLabel label = new JLabel("Splash Screen");
label.setFont(label.getFont().deriveFont(96f));
splashScreen.getContentPane().add(label, new GridBagConstraints());
splashScreen.pack();
splashScreen.setLocationRelativeTo(null);
splashScreen.setVisible(true);
new Thread(new Runnable() {
#Override
public void run() {
readDatabase();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}).start();
}
public void readDatabase() {
//simulate time to read/load data - 10 seconds?
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
public void createAndShowGUI() {
JLabel label = new JLabel("My Frame");
label.setFont(label.getFont().deriveFont(96f));
f.add(label);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
System.out.println("JFrame getAccessibleChildrenCount count -> "
+ SwingUtilities.getAccessibleChildrenCount(f));
System.out.println("JWindow getParent -> "
+ SwingUtilities.getWindowAncestor(splashScreen));
splashScreen.dispose();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Testing t = new Testing();
}
});
}
}
I did not go really into your design. but there is 'j.dispose();'.
this should work. here is the java documentation.
notice:
dispose(); - deletes the window from memory.
setVisibilty(false); - just hides it from the screen.
You can override the 'dispose()' function to do some stuff while the widow is closing (updating scores if its a game) but at the end of the overriden function you have to call 'super.dispose();' so the function of the class Window is called.
And the MainGame was a dialog window
But thats not what your code uses. You use a JWindow.
You should be using a JDialog for a modal window. Then you just dispose() the window.