how to use vlcj with java? - java

Hello Everyone i'm trying to use vlcj for java but am running into a lot of errors. I checked my jvm version and vlc media version both are 64 bit.
I tried a lot of codes that I had researched in the internet. I followed the step by inserting vlcj.jar in my code but nothing seems to work.
I followed the tutorial on caprica but it wouldn't work. Now i'm getting error
Exception in thread "main" java.lang.IllegalArgumentException: Interface (LibVlc) of library=libvlc does not extend Library B.
Can someone please help on this?
package mrbool.vlc.example;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.factory.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.binding.LibVlc;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import uk.co.caprica.vlcj.binding.RuntimeUtil;
public class JavaApplication1 {
public static void main(String[] args) {
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),"C:\\Program Files\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
MediaPlayerFactory factory = new MediaPlayerFactory();
}
}

install vlc media player in to same directory that your project is located

Sometimes the problem is due to incompatibility of the architecture of VLC and JRE.
You can check JRE architecture using the code below:
public class JavaApplication12 {
public static void main(String[] args) {
System.out.println(System.getProperty("sun.arch.data.model"));
}
}
EmbeddedMediaPlayerComponent mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
EmbeddedMediaPlayer embeddedMediaPlayer = mediaPlayerComponent.getMediaPlayer();
Canvas videoSurface = new Canvas();
videoSurface.setBackground(Color.black);
videoSurface.setSize(800, 600);
List<String> vlcArgs = new ArrayList<String>();
vlcArgs.add("--no-plugins-cache");
vlcArgs.add("--no-video-title-show");
vlcArgs.add("--no-snapshot-preview");
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory(vlcArgs.toArray(new String[vlcArgs.size()]));
mediaPlayerFactory.setUserAgent("vlcj test player");
embeddedMediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(videoSurface));
embeddedMediaPlayer.setPlaySubItems(true);
final PlayerControlsPanel controlsPanel = new PlayerControlsPanel(embeddedMediaPlayer);
PlayerVideoAdjustPanel videoAdjustPanel = new PlayerVideoAdjustPanel(embeddedMediaPlayer);
// mediaPlayerComponent.getMediaPlayer().playMedia(Constant.PATH_ROOT + Constant.PATH_MEDIA + "tmp.mp4");
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.setBackground(Color.black);
mainFrame.add(videoSurface, BorderLayout.CENTER);
mainFrame.add(controlsPanel, BorderLayout.SOUTH);
mainFrame.add(videoAdjustPanel, BorderLayout.EAST);
//create a button which will hide the panel when clicked.
mainFrame.pack();
mainFrame.setVisible(true);
embeddedMediaPlayer.playMedia("tmp.mp4");

Also, to do this yourself I would suggest using chrome. You just right click on whatever you want to scrape and go to inspect element. It will take you to the exact spot in the html where that element is located. In this case you first want to find out where the root of all the result listings are. When you find that, you want to specify the element, and preferably an unique attribute to search it by. In this case the root element i
public class ScanWebSO
{
public static void main (String args[])
{
Document doc;
try{
doc = Jsoup.connect("https://www.google.com/search?as_q=&as_epq=%22Yorkshire+Capital%22+&as_oq=fraud+OR+allegations+OR+scam&as_eq=&as_nlo=&as_nhi=&lr=lang_en&cr=countryCA&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=&as_rights=").userAgent("Mozilla").ignoreHttpErrors(true).timeout(0).get();
Elements links = doc.select("li[class=g]");
for (Element link : links) {
Elements titles = link.select("h3[class=r]");
String title = titles.text();
Elements bodies = link.select("span[class=st]");
String body = bodies.text();
System.out.println("Title: "+title);
System.out.println("Body: "+body+"\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}

Related

How to play a sound file in Java

I searched in many forums and YouTube tutorials for an easy bit of code to just play a sound file (.mp3), but everything I found won't work for me.
I always get the exception that it can't find the file or that something else is wrong, but it always ends in an exception.
Is there something that I have to configure first maybe?
-edit-
I tried the following code again to show what exeption i get:
Here is my code
After adding the JFXPanel i got the exeption: Exception in thread "main" MediaException: MEDIA_UNAVAILABLE : D:\bip.mp3 (The System cant find the File) //
and yes, i checked if the path is correct.
To avoid initialization Exception you have to either invoke Application.launch() method or simply instantiate a new JFXPanel() class (even if it isn’t used for anything). This will initiate JavaFxRuntime when application is started
so add below line in your code
final JFXPanel fxPanel = new JFXPanel();
Import following package
import javafx.embed.swing.JFXPanel;
Now your code will look like this
import java.io.File;
import javafx.embed.swing.JFXPanel;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class Test {
public static void main(String args[]) {
final JFXPanel fxPanel = new JFXPanel();
String bip = "D://bip.mp3"; //sound file path
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}
}
Maybe posting a specific error can solve your problem but anyways I think this can help you. And also I implemented it and works perfectly for me.
This is how I have done it:
List<Media> mediaList = new ArrayList<>();
FileManager files = new FileManager();
files.loadMediaFiles(new File("your music directory goes here.."));
files.getFiles().stream().forEach((media) -> {
mediaList.add(new Media(media));
});
MediaPlayer mediaPlayer = new MediaPlayer(playList.get(0));
MediaView mediaView = new MediaView(mediaPlayer);
playPauseButton.setOnAction((ActionEvent event) -> {
if (mediaPlayer.getStatus() == Status.PAUSED || mediaPlayer.getStatus() == Status.READY || mediaPlayer.getStatus() == Status.STOPPED) {
mediaPlayer.play();
playPauseButton.setGraphic(pause);
} else {
mediaPlayer.pause();
playPauseButton.setGraphic(play);
}
});
You can also checkout my app on github.

Set Icon Image in Java

I have been searching everywhere on how to set the icon image in Java, and it always ends up not working or it gives me errors. Here, in my main method is where I put the code:
public static void main(String[] args) {
Game game = new Game();
// This right here!
game.frame.setIconImage(new ImageIcon("/Icon.png").getImage());
game.frame.setResizable(false);
game.frame.setTitle(title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
}
My path for the image is "%PROJECT%/res/Image.png" and I just use /Image.png to go ahead and access my res folder (as I have done in other parts of my project) I have even converted it into an icon file, and tried that, but all it decides is to use the default Java icon.
Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.
e.g.,
// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);
// use icon here
game.frame.setIconImage(myImg);
Use Default toolkit for this
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:
IconImageUtilities.setIconImage(this);
The below method works well on Java 7 and above.
JFrame frame = new JFrame("MyAPP");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
frame.setIconImage(ImageIO.read(YourClass.class.getResourceAsStream("/icon.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
frame.setVisible(true);
Park your icon.png image file to /src/main/resources.

Can we compile a Java program inside an applet or a Swing window

Can we run a Java program in an applet window or a Swing window and how can we see the output of the compiled program?
You can use the Compiler API (available in Java 6) to compile sources.
You can either exec() the new process (if it has a main() entry) point, or use classloading to load it into your JVM. Note that if you take the latter course, you'll likely have to instantiate a new classloader each time - see here for more details.
You may have security concerns re. accessing the file system from an applet. As such you may be better off just using a standard Swing application (perhaps loaded using Java Web Start?)
Re. JavaCompiler API & Applet or Swing launched with JWS.
To compile source supplied in a text area, or by URL from the code-base would not require trust. OTOH the JavaCompiler is only available if the code is running in the JVM of a JDK (it requires the tools.jar to be on the run-time class-path). Applets and JWS based apps. are never run using a JDK and never have the tools.jar available.
See also
Example code for java compiler with a simple GUI code & discussion at OTN.
STBC (based on that code).
STBC Help. Goes into more detail on the tools.jar and the run-time class-path.
Example code
To avoid 'link rot', here is the code seen in that linked thread.
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import java.net.URI;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
/** A simple Java compiler with a GUI. Java 1.6+.
#author Andrew Thompson
#version 2008-06-13
*/
public class GuiCompiler extends JPanel {
/** Instance of the compiler used for all compilations. */
JavaCompiler compiler;
/** The name of the public class. For 'HelloWorld.java',
this would be 'HelloWorld'. */
JTextField name;
/** The source code to be compiled. */
JTextArea sourceCode;
/** Errors and messages from the compiler. */
JTextArea output;
JButton compile;
static int pad = 5;
GuiCompiler() {
super( new BorderLayout(pad,pad) );
setBorder( new EmptyBorder(7,4,7,4) );
}
/** A worker to perform each compilation. Disables
the GUI input elements during the work. */
class SourceCompilation extends SwingWorker<String, Object> {
#Override
public String doInBackground() {
return compileCode();
}
#Override
protected void done() {
try {
enableComponents(true);
} catch (Exception ignore) {
}
}
}
/** Construct the GUI. */
public void initGui() {
JPanel input = new JPanel( new BorderLayout(pad,pad) );
Font outputFont = new Font("Monospaced",Font.PLAIN,12);
sourceCode = new JTextArea("Paste code here..", 15, 60);
sourceCode.setFont( outputFont );
input.add( new JScrollPane( sourceCode ),
BorderLayout.CENTER );
sourceCode.select(0,sourceCode.getText().length());
JPanel namePanel = new JPanel(new BorderLayout(pad,pad));
name = new JTextField(15);
name.setToolTipText("Name of the public class");
namePanel.add( name, BorderLayout.CENTER );
namePanel.add( new JLabel("Class name"), BorderLayout.WEST );
input.add( namePanel, BorderLayout.NORTH );
compile = new JButton( "Compile" );
compile.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
(new SourceCompilation()).execute();
}
} );
input.add( compile, BorderLayout.SOUTH );
this.add( input, BorderLayout.CENTER );
output = new JTextArea("", 5, 40);
output.setFont( outputFont );
output.setEditable(false);
this.add( new JScrollPane( output ), BorderLayout.SOUTH );
}
/** Compile the code in the source input area. */
public String compileCode() {
output.setText( "Compiling.." );
enableComponents(false);
String compResult = null;
if (compiler==null) {
compiler = ToolProvider.getSystemJavaCompiler();
}
if ( compiler!=null ) {
String code = sourceCode.getText();
String sourceName = name.getText().trim();
if ( sourceName.toLowerCase().endsWith(".java") ) {
sourceName = sourceName.substring(
0,sourceName.length()-5 );
}
JavaSourceFromString javaString = new JavaSourceFromString(
sourceName,
code);
ArrayList<JavaSourceFromString> al =
new ArrayList<JavaSourceFromString>();
al.add( javaString );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter( baos );
JavaCompiler.CompilationTask task = compiler.getTask(
osw,
null,
null,
null,
null,
al);
boolean success = task.call();
output.setText( baos.toString().replaceAll("\t", " ") );
compResult = "Compiled without errors: " + success;
output.append( compResult );
output.setCaretPosition(0);
} else {
output.setText( "No compilation possible - sorry!" );
JOptionPane.showMessageDialog(this,
"No compiler is available to this runtime!",
"Compiler not found",
JOptionPane.ERROR_MESSAGE
);
System.exit(-1);
}
return compResult;
}
/** Set the main GUI input components enabled
according to the enable flag. */
public void enableComponents(boolean enable) {
compile.setEnabled(enable);
name.setEnabled(enable);
sourceCode.setEnabled(enable);
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
public void run() {
JFrame f = new JFrame("SSCCE text based compiler");
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
GuiCompiler compilerPane = new GuiCompiler();
compilerPane.initGui();
f.getContentPane().add(compilerPane);
f.pack();
f.setMinimumSize( f.getSize() );
f.setLocationRelativeTo(null);
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
/**
* A file object used to represent source coming from a string.
* This example is from the JavaDocs for JavaCompiler.
*/
class JavaSourceFromString extends SimpleJavaFileObject {
/**
* The source code of this "file".
*/
final String code;
/**
* Constructs a new JavaSourceFromString.
* #param name the name of the compilation unit represented
by this file object
* #param code the source code for the compilation unit
represented by this file object
*/
JavaSourceFromString(String name, String code) {
super(URI.create(
"string:///" +
name.replace('.','/') +
Kind.SOURCE.extension),
Kind.SOURCE);
this.code = code;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
Well applet is program which runs in background.For compiling a java program you'll need to access the local disk of client which IS NOT ALLOWED for an applet(According to my knowledge) due to security reasons.
What are you trying to achieve? I once tried to access a img file using applet.
Use Java Compiler API to translate source code into bytecode. After that use dynamic class loading to load compiled bytecode into jvm and launch it (to get output).
Also, if you want to do this from inside of java applet, you'll have to solve security issues.

Error: Could not find or load main class openWordDocument

I am trying to open Microsoft Word document using jacob.
Below is code:
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class openWordDocument {
private static final Integer wdNewBlankDocument = new Integer(0);
private static final Variant vTrue = new Variant(true);
private static final Variant vFalse = new Variant(false);
private static ActiveXComponent activeXWord = null;
private static Object activeXWordObject = null;
public static void main(String[] args) {
try {
activeXWord = new ActiveXComponent("Word.Application");
activeXWordObject = activeXWord.getObject();
Dispatch.put(activeXWordObject, "Visible", vTrue);
//activeXWordObject = null;
}
catch (Exception e) {
quit();
}
}
public static void quit() {
if (activeXWord != null) {
System.out.println("quit word");
//calls the Quit method of MS Word, this will close MS Word
activeXWord.invoke("Quit", new Variant[] {});
ComThread.Release();
activeXWord.release();
System.out.println("quit word");
}
}
}
When I am running above code getting error Error: Could not find or load main class openWordDocument
It's my mistake, I added .dll file in the classpath so I am unable to compile the java file. I removed that dll file after that, jvm started compiling and able to fine the class file.
Warning !!!
Check your external libraries (such as .jar files) path were added to to your project.
The path should have regular format. For example it supposed to not have special characters like as "+", ... or space.
I had that serious problem before in Eclipse IDE, change the path directory of my project library and then everything is okay again.

Code fails to show image - java.io.IOException at Image.createImage

I'm trying to create a splash screen using LWUIT. I want a form to load and display text and an imagefor 5 seconds then continue to the next form. I have a code but fails to show the image. The class and the image are stored together int he same package. Instead, it shows an error.
java.io.IOException
What could be the problem? This is the code
package tungPackage;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import javax.microedition.midlet.MIDlet;
public class photoMidlet extends MIDlet {
public void startApp() {
Display.init(this);
try {
Form splashscreen = new Form();
// Label splashText = new Label("Baldy");
Image image = Image.createImage("/splash.png");
Label pictureLabel = new Label(image);
splashscreen.addComponent(pictureLabel);
splashscreen.show();
} catch (Exception ex) {
Form x = new Form("ERROR");
String y = ex.toString();
Label g = new Label(y);
x.addComponent(g);
x.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Open your JAR file using a ZIP utility (e.g. 7-zip) and look in the root of the file. If splash.png isn't in the root of the jar that's your problem!
Place splash.png so it is in the root of the jar.

Categories