Documente Academic
Documente Profesional
Documente Cultură
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
INTERFUSER
Search
Home
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Size; import android.util.Log; import android.view.SurfaceHolder; public class SocketCamera { private static final String LOG_TAG = "SocketCamera:"; private static final int SOCKET_TIMEOUT = 1000; static private SocketCamera socketCamera; private CameraCapture capture; private Camera parametersCamera; private SurfaceHolder surfaceHolder; //Set the IP address of your pc here!! private final String address = "192.168.1.12"; private final int port = 9889;
private final boolean preserveAspectRatio = true; private final Paint paint = new Paint();
1 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
private int height = 320; private Rect bounds = new Rect(0, 0, width, height); private SocketCamera() { //Just used so that we can pass Camera.Paramters in getters and setters } parametersCamera = Camera.open();
capture.setCapturing(true); capture.start(); Log.i(LOG_TAG, "Starting Socket Camera"); } public void stopPreview(){ capture.setCapturing(false); }
public void setParameters(Camera.Parameters parameters) { //Bit of a hack so the interface looks like that of Log.i(LOG_TAG, "Setting Socket Camera parameters"); parametersCamera.setParameters(parameters); Size size = parameters.getPreviewSize(); bounds = new Rect(0, 0, size.width, size.height);
public void release() { Log.i(LOG_TAG, "Releasing Socket Camera parameters"); } //TODO need to implement this function
private class CameraCapture extends Thread private boolean capturing = false; public boolean isCapturing() { return capturing; }
2 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
synchronized (surfaceHolder) { Socket socket = null; try { socket = new Socket(); socket.bind(null);
c = surfaceHolder.lockCanvas(null);
socket.setSoTimeout(SOCKET_TIMEOUT);
InputStream in = socket.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in); //render it to canvas, scaling if necessary if ( bounds.right == bitmap.getWidth() && c.drawBitmap(bitmap, 0, 0, null); bounds.bottom == bitmap.getHeight()) {
if (preserveAspectRatio) {
dest = new Rect(bounds); dest.bottom = bitmap.getHeight() * bounds.right / bitmap.getWidth(); dest.offset(0, (bounds.bottom - dest.bottom)/2);
// do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { surfaceHolder.unlockCanvasAndPost(c); } }
} }
} }
Make sure that you change the ip address to that of your PC. Now we just need to make a few small modifications to the original CameraPreview. In this class look for the Preview class that extends the
3 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
SurfaceView. Now we just need to comments out three lines and replace them with our own:
class Preview extends SurfaceView implements SurfaceHolder.Callback { SurfaceHolder mHolder; //Camera mCamera; SocketCamera mCamera; Preview(Context context) { super(context);
// Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); //mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// The Surface has been created, acquire the camera and tell it where
Here i've change three lines: 1. Camera mCamera is replaced with SocketCamera mCamera 2. mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); is replaced with mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL); 3. mCamera = Camera.open(); is replaced with mCamera = SocketCamera.open();. So that's it.Now just make sure WebcamBroadcaster is running and start up the CameraPreview app in the Android emulator, you should now be seeing live previews in the emulator. Here's a short video of my emulator with the live preview: (Yes i know, it's me waving a book around)
4 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
Note: if the WebcamBroadcaster is not picking up your devices you most probably have a classpath issue. Make sure that you classpath points to the jmf.jar that is in the same folder as the jmf.properties file. If JMstudio works ok, its very likely that you have a classpath issue. Oh, one last thing. I also updated the WebCamBroadcaster so that it can be used with YUV format cameras, so here's the code for that as well:
package com.webcambroadcaster; import java.awt.Dimension;
import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream;
import javax.media.Buffer; import javax.media.CannotRealizeException; import javax.media.CaptureDeviceInfo; import javax.media.CaptureDeviceManager; import javax.media.Format; import import import import
import javax.media.Player;
* A disposable class that uses JMF to serve a still sequence captured from a * webcam over a socket connection. It doesn't use TCP, it just blindly * socket connection. * * @author Tom Gibara * */ * captures a still, JPEG compresses it, and pumps it out over any incoming
5 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
Vector<CaptureDeviceInfo> devices = CaptureDeviceManager.getDeviceList(null); for (CaptureDeviceInfo info : devices) { DataSource source; Format[] formats = info.getFormats(); for (Format format : formats) { if ((format instanceof RGBFormat)) { RGBFormat rgb = (RGBFormat) format; Dimension size = rgb.getSize(); if (size.width != width || size.height != height) continue; if (rgb.getPixelStride() != 3) continue; if (rgb.getBitsPerPixel() != 24) continue; if ( rgb.getLineStride() != width*3 ) continue; MediaLocator locator = info.getLocator(); source.connect(); System.out.println("RGB Format Found"); source = Manager.createDataSource(locator);
} else if ((format instanceof YUVFormat)) { YUVFormat yuv = (YUVFormat) format; Dimension size = yuv.getSize();
((CaptureDevice)source).getFormatControls()[0].setFormat(rgb);
if (size.width != width || size.height != height) continue; MediaLocator locator = info.getLocator(); source = Manager.createDataSource(locator); source.connect(); System.out.println("YUV Format Found");
return Manager.createRealizedPlayer(source);
} }
return null;
public static void main(String[] args) { int[] values = new int[args.length]; values[i] = Integer.parseInt(args[i]);
WebcamBroadcaster wb;
wb = new WebcamBroadcaster(values[0]);
6 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
wb.start();
public static final int DEFAULT_PORT = 9889; public static final int DEFAULT_WIDTH = 320;
public static final int DEFAULT_HEIGHT = 240; private final Object lock = new Object(); private final int width; private final int height; private final int port;
private boolean running; private Player player; private FrameGrabbingControl control; private boolean stopping; private Worker worker;
public WebcamBroadcaster(int width, int height, int port) { this.width = width; this.height = height; this.port = port;
public void stop() throws InterruptedException { synchronized (lock) { if (!running) return; if (player != null) { control = null; player.stop(); player = null;
7 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
private class Worker extends Thread { private final int[] data = new int[width*height]; @Override
BufferToImage btoi = new BufferToImage((VideoFormat)buffer.getFormat()); BufferedImage image = (BufferedImage) btoi.createImage(buffer); if (image != null) { OutputStream out = socket.getOutputStream();
DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(out)); for (int i = 0; i < data.length; i++) { dout.writeInt(data[i]); } dout.close();
socket = null; } catch (IOException e) { e.printStackTrace(); } finally { if (socket != null) try { socket.close(); /* ignore */
socket.close();
} catch (IOException e) { }
} }
try {
ss.close();
8 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
32 comments:
Hi
I'm also trying to put to work Tom Gibara's code. But i'm with a problem, i have the latest android sdk and it keeps giving me the error in the WebcamBroadcaster class in the following lines: import java.awt.Dimension;
import java.awt.image.BufferedImage; and import javax.imageio.ImageIO; It seems it cannot resolve this classes. What am i doing wrong? I take a look at my classpath and it is ok, just pointing to jmf.jar.
Separate Java application. It is not an Android app. It runs on you PC and broadcast frames from you web cam over a socket.
The Socket camera class, which is running as Part of the CameraPeview Activity in the emulator will then pick up the broadcast frames and display them in the emulator.
Hi, I had just tried to using live Camera on the emulator. And I had a trouble getting the WebcamBroadcaster work. Here is the error message I recieved:
----------------------------------------------Could not find the main class: WebcamBroadcaster. Program will exit. ----------------------------------------------Could you please help me with this? Thanks a lot. Ben
Not a lot for me to go on there Ben. But the WebcamBroadcaster is just a simple Java application, that can be run from the command line or run in an IDE such as Eclipse. This looks like a classpath set up issue to me. Have a look on the web for how to compile and run a basic java application.
9 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
Hi, I used your example of WebcamBroadcaster, but I had some problems. When I execute, it returns null when it tries to execute line 49, and thus it stops on line 157, and returns this message: "Unable to find a suitable player".
RGB or YUV Fomat connected to your PC. One way.. Go to JMStudio File->preferences, click on capture devices. If your web cam is not of these formats you'll have to modify the code as I did for the YUV format.
Hi, I got my program running but the emulator give black screen .. what is the problem?? can any one help me ?
I have the same problem as Laet. I keep getting the "Unable to find a suitable player" exception. I tried to detect my device from JMStudio and my webcam is detected and I can even capture using the File menu options in JMFStudio.
Also from the File->Preferences menu, it shows the following about my device Name = vfw:Microsoft WDM Image Capture (Win32):0 Locator = vfw://0 Output Formats----> 0. javax.media.format.YUVFormat
YUV Video Format: Size = java.awt.Dimension[width=160,height=120] yuvType = 32 StrideY = 320 StrideUV = 320 OffsetY = 0 OffsetU = 1 OffsetV = 3 1. javax.media.format.YUVFormat YUV Video Format: Size = java.awt.Dimension[width=176,height=144] yuvType = 32 StrideY = 352 StrideUV = 352 OffsetY = 0 OffsetU = 1 OffsetV = 3 2. javax.media.format.YUVFormat YUV Video Format: Size =
java.awt.Dimension[width=320,height=240] MaxDataLength = 153600 DataType = class [B yuvType = 32 StrideY = 640 StrideUV = 640 OffsetY = 0 OffsetU = 1 OffsetV = 3
3. javax.media.format.YUVFormat YUV Video Format: Size = java.awt.Dimension[width=352,height=288] MaxDataLength = 202752 DataType = class [B
10 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
yuvType = 32 StrideY = 704 StrideUV = 704 OffsetY = 0 OffsetU = 1 OffsetV = 3 4. javax.media.format.YUVFormat YUV Video Format: Size = java.awt.Dimension[width=640,height=480] MaxDataLength = 614400 DataType = class [B yuvType = 32 StrideY = 1280 StrideUV = 1280 OffsetY = 0 OffsetU = 1 OffsetV = 3
Any suggestions?
Check that: 1) Your Preview Class has the following (original) methods
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(w, h);
mCamera.setParameters(parameters); mCamera.startPreview(); } 2) Your Manifest File contain CAMERA and INTERNET User permissions.
Don't forget that for the emulator it is necessary to have a proper internet address. In this case, since you are using the emulator in the same have to use "10.0.2.2" as your address.
But I have a question, If I want change the webcam to another entity phone, How should i do it?
Hi, this is a really great job, but the problem is that I don't know how to make it run xD. Can you help me?? What's the code I need to add to the onCreate Activity method?? Thx.
11 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
recognize the webcam on my computer and your camera to run applications from my computer as Layar. Working from the Eclipse IDE where I have an activity / application with your code and SurfaceWiew SocketCamera (which are 2 necessary as I understand).
Emitted from JMF with my cam RGB to IP 127.0.0.1 port 8888 which is the IP I set in the program.
Not what I'm doing wrong but when running the application gives me error: java.lang.RuntimeException and java.lang.IllegalAccesException. Anyone can help me? Thanks.
SocketCamera. They are on my blog, but it's in italian, so if any english user is interested i paste methods here. (maybe not the best code but it works) // Prova per takePicture public final void
takePicture(Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback jpeg) { takePicture(shutter, raw, null, jpeg); }
public final void takePicture(Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback postview, Camera.PictureCallback jpeg) { stopPreview();
ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object byte[] b = baos.toByteArray();
// Chiama la callback if (raw != null) raw.onPictureTaken(b, null); if (postview != null) postview.onPictureTaken(b, null);
12 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
if (jpeg != null) jpeg.onPictureTaken(b, null); } catch (RuntimeException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close();
1- If i remember right 127.0.0.1 it's the loopback address of the emulator and if u want to connect to your Computer u must use the explicit ip addres of computer or 10.0.2.2 (see networking
under android emulator on android sdk pages) 2- IllegalAccesException point me to permissions of your Code, check the AndroidManifest if u have added permission for both CAMERA and INTERNET. Elsewhere i can't help, sorry.
hi,
exactly which of the files required, do i have to add the all of others on the tom gibara's page?
hi, very useful work,i'm working on a android application and i need to be able to use my
laptop webcam to go one step forward in my project..but everytime i run your work i get an error:
"The application ...(process ...)has stopped unexpectedly.Please try again." Can anyone know how to get rid of this error, please someone help me, thanks in andvance
hi,
i can run the code successfully with any error, however, the webcam image can't be shown in the emulator. 3 question i would like to ask:
1. how can i ensure the broadcaster is running successfully? i compile it and it shows the following:
13 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
3. what IP address in the SocketCamera? i tried 10.0.0.2 (my computer's IP), 10.0.2.2 and 127.0.0.1, all don't work. anyone can help? thanks!!
Harry: 1.broadcaster is fine(on port 9889) 2.no 3.i just did ipconfig and set the address(192.168.xx.xx) in socketcamera.
Anonymous has left a new comment on your post "Live camera preview in the Android emulator": Hello Neil,thanks a lot for this post....i got it working with a Frontech webcam on XP.
For the benefit of the readers,apart from the changes that u hv mentioned above,the following should be entered in the manifest file: uses-permission
android:name="android.permission.CAMERA" uses-permission android:name="android.permission.INTERNET" The first one is reqd when we are doing
Camera.open() and the next one for the socket connection. I had another problem in teh manifest file,that
being a mismatch between the activity name,which should be CameraPreview if we are directly using your source files. Thanks again... Biswajit Goswami
Hi,
I used the same code but it doesn't work for me. the question that I want to ask is: it run and also the level thanks what is the version of sdk that you used to make
Express. The code is working fine. I just do not get a picture from the camera. I only get black with white noise. It's the same in JM studio. I guess this is a problem with my cam driver, or am i wrong???
14 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
Hi, I tried to make this code to work but I don't see the code of Activity to launch the screen so please can you help me thanks
hi, i don't know what's wrong but I was having hard time getting the emulator detect the
camera. I checked the JMStudio and it worked well, I also classpath and path but still not working.
Now, I'd like to create some shape over the camera view. Can anyone help me?
java files that are required for using webcam in android emulator?...Also, please provide some step-by-step instructions as to which file should go where....I am working on a Barcode Scanner project and I am not able to get the emulator
camera work, so any help is greatly appreciated......I tried some of the steps here and also from Tomgibara's site...but I am not able to understand which files should go where and what code i should include in my Activity.......Also, i am having trouble with the webcambroadcaster file, which keeps giving me errors, so is many other files. I followed the steps mentioned below, but i have so many errors when i include the files in my project......http://stackoverflow.com /questions/1276450/how-to-use-web-camerain-android-emulator-to-capture-a-live-image.
Please also mention the sdk and jdk versions to use in order to run these files... Thanks in advance and please try to reply early.
can anyone post the original CameraPreview class?It seems a lot of the functions have been
android said...
Hello friends....Can anyone please post all the java files that are required for using webcam in
15 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
android emulator?...Also, please provide some step-by-step instructions as to which file should go where....I am working on a Barcode Scanner project and I am not able to get the emulator camera work, so any help is greatly appreciated
and how can i get the port number pleas any one reply
guy, I get error: java.io.IOException: Could not connect to capture device not connecting in WebcamBroadcaster if you can help me
nice,am very impresed on that.I try to create android mobile captured video stream to server
using RTSP/RTP.I am a android fresher please can u guide me. Mail ID== roy8086@gmail.com All ideas are welcome Thanks Roy
Tomgibara's code. I have tried to execute both, Webcambroadcaster and SocketCamera. I don't know if it's correct, my webcambroadcaster shows like someone's above: RGB Format Found Starting the player Grabbing frames And my socketcamera still shows that chess picture in instead of my webcam. What am I doing wrong? I noticed indeed Webcambroadcaster stops on: socket = ss.accept(); I also create an entry on firewall 4 port 9889. Thanxs in advance.
Post a Comment
16 of 17
9/5/2011 1:00 PM
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emu...
Home
Older Post
17 of 17
9/5/2011 1:00 PM