I am trying to run code, but this error shows up. I am using Netbeans on windows, jdk-9, javacv 1.3.2, opencv 3.1.0-1.2. What could be the solution to this?
Part from the main code:
public void start() {
frameGrabber = new FFmpegFrameGrabber("video=Webcam C170");
frameGrabber.setFormat("dshow");
frameGrabber.setImageWidth(1280);
frameGrabber.setImageHeight(720);
logger.debug("Starting frame grabber");
try {
frameGrabber.start(); //line 72
logger.debug("Started frame grabber with image width-height : {}-{}", frameGrabber.getImageWidth(), frameGrabber.getImageHeight());
} catch (FrameGrabber.Exception e) {
logger.error("Error when initializing the frame grabber", e);
throw new RuntimeException("Unable to start the FrameGrabber", e);
}
SwingUtilities.invokeLater(() -> {
window.setVisible(true);
});
process();
logger.debug("Stopped frame grabbing.");
}
Error:
Caused by: org.bytedeco.javacv.FrameGrabber$Exception: avformat_open_input() error -5: Could not open input "video=Webcam C170". (Has setFormat() been called?)
at org.bytedeco.javacv.FFmpegFrameGrabber.startUnsafe(FFmpegFrameGrabber.java:535)
at org.bytedeco.javacv.FFmpegFrameGrabber.start(FFmpegFrameGrabber.java:465)
at org.imesha.examples.javacv.JavaCVExample.start(JavaCVExample.java:72)
Did you try to pass filename as constructor parameter, but with extension? Based on source file the FFmpegFrameGrabber has 3 constructors and one of option is to pass a String called filename, which mostly means a file name + its extension like "yourfile.mpeg"
Related
I have a Java application, and when I use java.awt.Desktop:
Desktop.getDesktop().open(file);
It works fine on Windows (opens a file in my default program), but on Ubuntu (with openJdk 13), the Java application gets stuck and I do not even get any log error or anything. I have to force quit the app in order to recover.
The file path it correct, otherwise I would actually get an Exception. Also, isDesktopSupported a isSupported(Action.OPEN) returns true.
What can I do? Can I check some system settings or logs? Or perhaps get some logs from java.awt.Desktop? Or does this not work on Ubuntu/Linux?
Are there any alternatives?
From here:
In order to use the API, you have to call java.awt.EventQueue.invokeLater() and call methods of the Desktop class from a runnable passed to the invokeLater():
void fxEventHandler() {
EQ.invokeLater(() -> {
Desktop.open(...);
});
}
I am just going to add an example function
private static void OpenFile(String filePath){
try
{
//constructor of file class having file as argument
File file = new File(filePath);
if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not
{
System.out.println("not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) { //checks file exists or not
EventQueue.invokeLater(() -> {
try {
desktop.open(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
I am trying to print an HTML file using java.awt.Desktop.print but the print dialog throws an IOException.
menuPrint.setOnAction((ActionEvent t) -> {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.PRINT)) {
try {
File output = new File(System.getProperty("java.io.tmpdir")+"/Preview.html");
desktop.print(output);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
java.io.IOException: Failed to print C:\Users\XXX\AppData\Local\Temp\Preview.html.
Error message: A device attached to the system is not functioning.
I have a PDF printer installed and can open the print dialog using Ctrl+P. Though this same code is working on a separate machine which is connected to an actual printer.
Any clues appreciated. How to make it work?
I'm trying to play sound in Java but it doesn't work and I got error message.
Here is my Code
public class PlaySoundClip extends JFrame {
public PlaySoundClip() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
this.setVisible(true);
try {
URL url = this.getClass().getClassLoader().getResource("click.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);//Line 27
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY); // repeat forever
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new PlaySoundClip();//Line 44
}
}
And I get this error message then I'm not here any sound! How to fix this problem?
Exception in thread "main" java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(StandardMidiFileReader.java:205)
at javax.sound.midi.MidiSystem.getSequence(MidiSystem.java:836)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:174)
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1145)
at playsoundclip.PlaySoundClip.<init>(PlaySoundClip.java:27)
at playsoundclip.PlaySoundClip.main(PlaySoundClip.java:44)
Reference from Playing Sound.
Something is wrong with click.wav, it was not found on the classpath, so url became null, hence the NullPointerException.
You should put the click.wav on your classpath, so the program will find it. The most straightforward way is putting into the root folder of the jar file.
Most likely in your build phase there is a list of "resources" that are copied from source tree to the output compiled classes. Usually it is a string of regular expressions like ".txt;.json;…" In your case you need to add ".wav" to it or copy file by hand to the compiler output location.
Most IDEs (Eclipse|IteliJ IDEA) and some ant build scripts have provision for resource copying.
I am getting a FileNotFoundException while running code.
my filname is filecontent.java...
Definition: I want to create a program having 4 TextFields and 4 TextAreas. If one types the name of the file in TextField, then its content should be shown in corresponding TextArea.
Error :
Exception e : java.io.FileNotFoundException :
My Code :
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class filecontent extends Frame implements ActionListener
{
TextField t[]=new TextField[4];
TextArea ta[]=new TextArea[4];
Button submit,exit=new Button("Exit");
Panel p1;
filecontent()
{
setGUI();
setRegister();
try{
showfile();
}
catch(IOException ioe)
{
System.out.println("Exception e : "+ioe);
}
setTitle("FileData");
setVisible(true);
setSize(300,300);
setLocation(500,200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent we)
{ System.exit(0); }
});
}
void setGUI()
{
p1=new Panel();
p1.setLayout(new GridLayout(5,4,10,10));
for(int i=0;i<4;i++)
{
t[i]=new TextField(10);
ta[i]=new TextArea();
p1.add(t[i]);
p1.add(ta[i]);
}
submit=new Button("Submit");
p1.add(submit);
p1.add(exit);
}
void setRegister()
{
submit.addActionListener(this);
exit.addActionListener(this);
}
void showfile() throws java.io.IOException
{
FileReader fin[]=new FileReader[4];
FileReader fn=new FileReader("filecontent.java");
BufferedReader br[]=new BufferedReader[4];
for(int i=0;i<4;i++)
{
fin[i]=new FileReader(t[i].getText());
}
int cnt=1;
String s;
fn=fin[0];
br[0]=new BufferedReader(fn);
while(cnt<=4)
{
if((s=br[cnt-1].readLine())!=null)
{
ta[cnt-1].append(s+"");
}
else
{
fin[cnt-1].close();
cnt++;
fn=fin[cnt-1];
br[cnt-1]=new BufferedReader(fn);
ta[cnt-1].setText("");
}
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try{
showfile();
}
catch(IOException ioe)
{
System.out.println("Exception e"+ioe);
}
}
else if(ae.getSource()==exit)
{
System.exit(0);
}
}
public static void main(String ar[])
{
new filecontent();
}
}
You don't have a NullPointerException. You have a FileNotFoundException. As the name of this exceptions says this is because a file you try to open isn't found.
The first file access that fails is this one:
FileReader fn=new FileReader("filecontent.java");
If your java file is located within a src (or any other) folder of your project you have to add the folder. E.g. src/filecontent.java
Some other notes:
By convention java class names start with upper case letters
Your variable names t, ta, p1, etc. can be confusing. Why not use textFields, textAreas, panel?
I think you will run into an ArrayIndexOutOfBoundsException in this line while(cnt<=4)
. Array indices start with 0 and end with n - 1 (=3 in your case)
It can help debuging to print out the stacktrace in your catch block: ioe.printStackTrace(). This gives you the exact line number where your code fails
Your exception may have come from this line
FileReader fn=new FileReader("filecontent.java");
I think you should use a full path, not just a file name.
First of all, why don't you use FileDialog instead of textField for the file. Secondly, you are using relative path so for your program to work, the file filecontent.java must be in the same place as your .class file
When reading a file in java the syntax for filepath varies system to system. So you should apply the path according to the operating system you are using.
Also for your code the file filecontent.java should be in the same directory.
Based on your comments, the answer is that the file appears as a.txt in explorer but is actually a.txt.txt Showing file extensions in explorer avoids this issue/confusion.
When you use a file path it is relative to the working directory, i.e. where the application was run. Not where the source code can be found. If you don't know what your working directory is, you should use a full path name.
I'm writing a screencast application in Java.
I decided to use Xuggle to do it and I followed up the installation instructions on the xuggle wiki.
I set up the PATH environment with %XUGGLE_HOME%\bin and %XUGGLE_HOME%\lib. Everything seems OK.
I made this application as a RCP plugin. I tried it on the "RCP-mail" template and the plugin is working and the video is generated correctly.
But when I decided to use it on a "real" application, the plug-in crashed with a strange error message:
Starting Capture
2011-11-10 08:08:45,438 [Thread-5] WARN com.xuggle.ferry.JNILibraryLoader - Failure: library load of library: xuggle-xuggler; version: 3: absolute path: C:\Program Files (x86)\Xuggle\bin\libxuggle-xuggler-3.dll; error: java.lang.UnsatisfiedLinkError: C:\Program Files (x86)\Xuggle\bin\libxuggle-xuggler-3.dll: Can't find dependent libraries
2011-11-10 08:08:45,447 [Thread-5] WARN com.xuggle.ferry.JNILibraryLoader - Failure: library load of library: xuggle-xuggler; version: 3: absolute path: C:\Program Files (x86)\Xuggle\bin\libxuggle-xuggler-3.dll; error: java.lang.UnsatisfiedLinkError: C:\Program Files (x86)\Xuggle\bin\libxuggle-xuggler-3.dll: Can't find dependent libraries
2011-11-10 08:08:45,453 [Thread-5] ERROR com.xuggle.ferry.JNILibraryLoader - Could not load library: xuggle-xuggler; version: 3; Visit http://www.xuggle.com/xuggler/faq/ to find common solutions to this problem
But this strange because the java.library.path is well defined:
logger.info(System.getProperty("java.library.path"));
returns
Nov 10, 2011 8:08:45 AM com.gvs.tools.ui.record.video.handler.RecordHandler startRecording
INFO: C:\Program Files (x86)\Java\jre6\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files (x86)/Java/jre6/bin/client;C:/Program Files (x86)/Java/jre6/bin;C:/Program Files (x86)/Java/jre6/lib/i386;C:\Program Files (x86)\Xuggle\bin;C:\Program Files (x86)\Xuggle\lib;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\JProbe 8.3\bin;C:\Program Files\TortoiseSVN\bin;D:\Work\Paul\eclipse;;.
What I'm missing to make the plug-in work with this application?
Is this issue due to the fact that the application uses other native libraries such as 3D-dll?
Here is the code used to make the screencast video:
RecordHandler.java:
private void startRecording() {
Logger logger = Logger.getLogger(RecordHandler.class.getName());
logger.info(System.getProperty("java.library.path"));
// Initialize framesQueue
framesQueue = new LinkedBlockingQueue<BufferedImage>();
// Initialize the capture thread
captureThread = new ScreenCapturer();
captureThread.setCaptureFramesQueue(framesQueue);
// Initialize the recorder
encoderThread = new FrameEncoder("test.mp4");
encoderThread.setCapturedFramesQueue(framesQueue);
// Start capture
captureThread.start();
// wait for the Queue to be feed before encoding
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
encoderThread.start();
}
ScreenCapturer.java:
#Override
public void run() {
// Retrieve the application main window's shell
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
appShell = Display.getCurrent().getActiveShell();
}
});
isRunning = true;
System.out.println("Starting Capture");
for (numberOfFramesTaken = 0; isRunning && numberOfFramesTaken <= IVideoEncoderConfiguration.MAXIMUM_NUMBER_OF_FRAMES; numberOfFramesTaken++) {
try {
takeScreenShot();
Thread.sleep(IVideoEncoderConfiguration.CAPTURE_TIME_INTERVAL_MILLIS);
} catch (InterruptedException e) {
}
}
System.out.println("Capture has ended");
System.out.println("Number of frames taken: "
+ numberOfFramesTaken);
}
/**
* Take a screen capture and store it in the capturedFramesQueue
*/
private void takeScreenShot() {
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
if (appShell != null) {
Rectangle bounds = appShell.getBounds();
java.awt.Rectangle awtBounds = new java.awt.Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
final BufferedImage screenCapture = robot.createScreenCapture(awtBounds);
try {
capturedFramesQueue.put(screenCapture);
} catch (InterruptedException e) {
}
}
}
});
}
FrameEncoder.java:
public void run() {
isRunning = true;
String outFile = outputdirectoryPath + outputFileName;
// First, let's make a IMediaWriter to write the file.
final IMediaWriter writer = ToolFactory.makeWriter(outFile);
// Retrieve the first frame to guess video dimensions
BufferedImage firstFrame = null;
try {
firstFrame = capturedFramesQueue.take();
} catch (InterruptedException e) {
}
if (firstFrame == null) {
return;
}
// We tell it we're going to add one video stream, with id 0,
// at position 0, and that it will have a fixed frame rate of
// FRAME_RATE.
writer.addVideoStream(0, 0,
IVideoEncoderConfiguration.FRAME_RATE,
firstFrame.getWidth(), firstFrame.getHeight());
long startTime = System.nanoTime();
for (numberOfFramesRecorded = 0; isRunning
&& numberOfFramesRecorded <= IVideoEncoderConfiguration.MAXIMUM_NUMBER_OF_FRAMES; numberOfFramesRecorded++) {
// Retrieve the captured frame
try {
final BufferedImage currentFrame = convertToType(capturedFramesQueue.take(), BufferedImage.TYPE_3BYTE_BGR);
// encode the next frame
writer.encodeVideo(0, currentFrame, System.nanoTime() - startTime,
TimeUnit.NANOSECONDS);
// sleep, time depending of FRAME_RATE
Thread.sleep(IVideoEncoderConfiguration.CAPTURE_TIME_INTERVAL_MILLIS);
} catch (InterruptedException e) {
}
}
// Get the remaining frame on the queue
Collection<BufferedImage> frames = new LinkedList<BufferedImage>();
capturedFramesQueue.drainTo(frames, IVideoEncoderConfiguration.MAXIMUM_NUMBER_OF_FRAMES - numberOfFramesRecorded);
for (BufferedImage frame : frames) {
BufferedImage currentFrame = convertToType(frame, BufferedImage.TYPE_3BYTE_BGR);
writer.encodeVideo(0, currentFrame, System.nanoTime() - startTime,
TimeUnit.NANOSECONDS);
}
// close the MediaWriter, write the trailer if needed
writer.close();
}
It's a little late I know, but the problem is that Xuggler requires ALL THE DLLs to be in the operating system load-path environment, not just the java.library.path
That means that all DLLs that install with Xuggle (for example, libavcodec.dll) need to be in the %PATH% environment variable of the process that launched Java.
Cause Could be un-availability of dependency jars or version conflicts.
Adding the following jars in the class path worked fine for me:
xuggle-xuggler-5.4.jar
slf4j-api-1.6.4.jar
logback-core-1.0.0.jar
logback-classic-1.0.0.jar