ここで説明されているようにカメラを使用しています: Android Camera will not work. startPreview が失敗します。バックカメラを使えば問題なく動きます!プレビューが機能し、写真を撮ることができます。
ただし、パラメーターを設定して前面カメラを使用するparameter.set("camera-id", 2)
と、メソッドでエラーがスローされますcamera.takePicture(...)
。プレビューは問題なく動作し、SurfaceView で自分自身を見ることができます。でも写真が撮れない。
エラーは次のとおりです。
> 07-24 21:59:52.926: E/AndroidRuntime(2462): Caused by: java.lang.RuntimeException:
> takePicture failed
> at android.hardware.Camera.native_takePicture(Native Method)
> at android.hardware.Camera.takePicture(Camera.java:672)
> at android.hardware.Camera.takePicture(Camera.java:636)
> at org.omich.alarm.PhotoController.takePhoto(PhotoController.java:94)
> ... 15 more
これが私のコードです:
public class Photo
{
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
private CameraCallback mCameraCallback;
public Photo (Activity context)
{
mSurfaceView = (SurfaceView)context.findViewById(R.id.surfaceView);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(new SurfaceCallback());
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void takePhoto ()
{
if(mCameraCallback == null)
{
mCameraCallback = new CameraCallback();
}
try
{
mCamera.takePicture(null, null, mCameraCallback);
}
catch (Throwable e)
{
Log.d("ERROR!!! takePicture error");
}
}
//========================================================================
// private int getFrontCameraId()
// {
// CameraInfo ci = new CameraInfo();
// for (int i = 0 ; i < Camera.getNumberOfCameras(); i++)
// {
// Camera.getCameraInfo(i, ci);
// if (ci.facing == CameraInfo.CAMERA_FACING_FRONT)
// {
// return i;
// }
// }
// return -1; // No front-facing camera found
// }
private static class CameraCallback implements Camera.PictureCallback
{
@Override
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Yahoo! Photo taken");
}
}
private class SurfaceCallback implements SurfaceHolder.Callback
{
//==== SurfaceHolder.Callback ============================================
@Override
public void surfaceChanged(SurfaceHolder arg0, int format, int width, int height)
{
Camera camera = mCamera;
Parameters p = camera.getParameters();
if(p != null)
{
p.setPreviewSize(width, height);
p.set("camera-id", 2);
camera.setParameters(p);
}
try
{
camera.setPreviewDisplay(mSurfaceHolder);
camera.startPreview();
}
catch (IOException e)
{
Log.d("setPreviewDisplay error");
}
catch (Throwable e)
{
Log.d("startPreview error");
}
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
// mCamera = Camera.open(getFrontCameraId());
mCamera = Camera.open();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
}