Taking Snapshots from a Webcam using JMF - java

I want to take a snapshot from a webcam through java. I followed this question and arrived at the this example. But there is a null pointer exception coming from the below line -
Buffer buf = frameGrabber.grabFrame();
Image img = (new BufferToImage((VideoFormat) buf.getFormat())
.createImage(buf));
buffImg = new BufferedImage(img.getWidth(this), img.getHeight(this),
BufferedImage.TYPE_INT_RGB);
Through the debugger I observed that the buffer doesn't actually contain data. So I went the creation of frameGrabber.
frameGrabber = (FrameGrabbingControl) player
.getControl("javax.media.control.FrameGrabbingControl");
Is there a problem with this code. Because JMFStudio works fine in my machine but the code cannot access it. Thank you.

I found the solution. The JMF needs time for initialization. In the example we have to switch a line. Put the
new Timer(3000, this).start();
below the try catch.
The whole block looks like below.
try {
player = Manager.createRealizedPlayer(cdi.getLocator());
player.start();
} catch (NoPlayerException e) {
e.printStackTrace();
} catch (CannotRealizeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Timer(3000, this).start();
// Grab a frame from the capture device
frameGrabber = (FrameGrabbingControl) player
.getControl("javax.media.control.FrameGrabbingControl");

Related

Zxing - UPC +5 Supplement Barcode Detection

I have been attempting to use Zxing 2.3.0 to read images of UPC barcodes with a +5 supplement in java however i cannot read the supplement portion of the barcode. The code successfully reads the first portion only. After searching multiple websites i cannot find any further indications of how to read the supplement other than my current method. Any help would greatly be appreciated.
public static void main(String[] args) {
decodeUPC5();
}
public static void decodeUPC5(){
InputStream barCodeInputStream = null;
try {
barCodeInputStream = new FileInputStream("C:/Users/apoclyps/git/zxing-barcoder/Zxing-Test/img/upc5.png");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedImage barCodeBufferedImage = null;
try {
barCodeBufferedImage = ImageIO.read(barCodeInputStream);
} catch (IOException e) {
e.printStackTrace();
}
LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
// Attempting to read UPC + 5 Supplement
GenericMultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(new MultiFormatReader());
try {
multiReader.decodeMultiple(bitmap);
} catch (NotFoundException e1) {
e1.printStackTrace();
}
Result[] result = null;
try {
result = multiReader.decodeMultiple(bitmap);
} catch (NotFoundException e) {
e.printStackTrace();
}
System.out.println("Results length "+result.length);
for(Result r : result ){
System.out.println("Barcode text is " + r.toString());
}
}
Barcode image!
Output
Results length 1
Barcode text is 9780735200449
Keep in mind that the content of the barcode is 9780735200449 and not 9780735200449 51299. It will always (correctly) return the 9780735200449 as the contents of the barcode.
The +5 extension is returned as ResultMetadata, under key ResultMetadatatype.UPC_EAN_EXTENSION.
Note that it will still return the UPC barcode even if it doesn't see a +5 extension, obviously. So it's possible you would see it return without a +5 extension on this image. However it works for me with the app and so would imagine it easily detects the +5. (If you scan with the app, look at the left for "Metadata $12.99")

Re-reading a file after EOF using NIO (Java)

I'm using MemoryMapped buffer to read a file. Initially I'm getting the channel size and using the same size I"m mapping the file on memory and here the initial position is 0 as I want to map the file from the beginning. Now another 400KB of data is added to that file, now I want to map that 400kb alone. But something is wrong in my code, I'm not able to figure it out and I'm getting this
260java.io.IOException: Channel not open for writing - cannot extend file to required size
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:812)
at trailreader.main(trailreader.java:55
So here's my code
BufferedWriter bw;
FileInputStream fileinput = null;
try {
fileinput = new FileInputStream("simple.csv");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileChannel channel = fileinput.getChannel();
MappedByteBuffer ByteBuffer;
try {
ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Add some 400 bytes to simple.csv. outside of this program...
*/
//following line throw exception.
try {
ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, channel.size(), 400);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So in my code I'm trying to reread the additional data that has been added but its not working, I know the prob is channel.size(), but I'm not able to rectify it.
channel.size() is always the current end of file. You are attempting to map 400 bytes past it. It isn't there. You need something like:
ByteBuffer = fileinput.getChannel().map(FileChannel.MapMode.READ_ONLY, channel.size()-400, 400);

Finding Duration of an MP3 file in Java

OK so I have tried using ID3 tags to get the duration and I also tried using JMF media player.getDuration().
player.getDuration().getSeconds()
The file is VBR. Are there any light weight libraries or something inside JMF that could be used to solve this problem.
Thanks.
I use JAudioTagger to achieve this. The below code will get you the duration of an MP3 track.
int duration = 0;
try {
AudioFile audioFile = AudioFileIO.read(new File("file.mp3"));
duration = audioFile.getAudioHeader().getTrackLength();
} catch (Exception e) {
e.printStackTrace();
}
You can alternatively cast audioFile.getAudioHeader() to MP3AudioHeader and use the method getPreciseTrackLength() to get a more precise duration. However, this (i believe) only applies to MP3 files and no other formats (such as WAV files).
I using this lib and this code :
File f = new File("path/mp3");
MediaLocator ml = null;
Player p = null;
try {
ml = new MediaLocator(f.toURL());
p = Manager.createPlayer(ml);
p.start();
while (true) {
Thread.sleep(1000);
System.out.println("Media Time :: "+p.getMediaTime().getSeconds());
System.out.println("Duration :: "+p.getDuration().getSeconds());
if(p.getMediaTime().getSeconds() == p.getDuration().getSeconds())
break;
}
p.stop();
p.deallocate();
p.close();
} catch (NoPlayerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Good luck.

JAVA + try catch(FileNotFoundException e) going in catch(Exception e)?

I have some command which creates a file on disk.
Because the folder in which the file has to be created is dynamic, I have a catch(FileNotFoundException e). In the same try block, I already have a catch(Exception e) block.
For some reason, when I run my code and the folder does not exists yet, the catch(Exception e) block is used, not the FileNotFoundException one.
The debugger is clear though (to me at least), showing a FileNotFoundException: java.io.FileNotFoundException: c:\mydata\2F8890C2-13B9-4D65-987D-5F447FF0DDA7\filename.png (The system cannot find the path specified)
Any idea why it doesn't go into the FileNotFoundException block?
Thanks;
CODE:
import java.io.FileNotFoundException;
try{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
catch (FileNotFoundException e){
// do stuff here..
return false;
}
catch(Exception e){
// do stuff here..
return = false;
}
It's also possible that the specific issue you're having isn't a FileNotFoundException. By using the "Exception" in a catch block (which is the parent class to all Exceptions) this is effectively a "catch all", since it will run if there is an `Exception or any of its subclasses thrown.
Try the following change:
...
catch (Exception e) {
System.out.println(e.getClass());
}
...
This will tell you the specific class of the Exception being caught by this block. I'll bet you'll find that the Exception is actually an instance of a subclass (such as IOException, for example).
Your problem is that the FileNotFoundException is thrown somewhere deep inside the java library and not propagated up so you cannot catch it.
The real culprit here is a NullPointerException originating from the
ImageIO.write(image, "png", new File(fileName));
call. This one runs into your catch (Exception e) block.
If you add a catch (NullPointerException e) block before your general Exception catch, you will see it going in there.

Jar with compressed music with java?

I've tried to add music to an application I've made. First I tried with .wav files though they became so huge that the application became too large to upload anywhere.
So I changed the files to .mp3, tried JMF and JLayer though both of them won't work on runnable jars (even if they work fine when I haven't exported them).
So anyone got any tips on how to play compressed music with a runnable jar?
Here's the code for JLayer, when exported it stops working at f = new File(u.toURI()) without throwing any exceptions...
try {
URL u = cl.getResource("New Beginnings.mp3");
f = new File(u.toURI());
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream(f);
p = new Player(fis);
p.play();
} catch (Exception e) {
System.out.println(e);
}
Edit: Fixed with changing the above code to:
try {
InputStream fis = ClassLoader.getSystemClassLoader().getResourceAsStream(temp+".mp3");
p = new Player(fis);
p.play();
} catch (Exception e) {
System.out.println(e);
}
Where did you place the sound file exactly?
You should create a new package inside your project and place the resources there, then read the file by sending a complete path:
ex. create a new package called sounds, then:
InputStream fis = ClassLoader.getSystemClassLoader().getResourceAsStream("/sounds/"+temp+".mp3");
p = new Player(fis);
p.play();
To be honest, I didn't try it with sounds, but this problem happened to me when I used images. I placed them in a package, and everything worked fine..

Categories

Resources