android相机对象总是一个空指针

时间:2014-12-30 15:40:59

标签: android surfaceview video-capture android-mediarecorder null-pointer

我调用这个方法,它给了我一个摄像头对象是recorder.setCamera(this.camera)调用的空指针

    private void initRecorder()
{
    if(camera == null)
    {
       camera = Camera.open();
       camera.unlock();
    }
    recorder.setCamera(this.camera);
    recorder.setPreviewDisplay(holder.getSurface());
    recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
    recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    recorder.setVideoFrameRate(60);

    CamcorderProfile cpHigh = CamcorderProfile.get(cameraInfo.facing,CamcorderProfile.QUALITY_HIGH);
    recorder.setProfile(cpHigh);
    String fileName = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
    recorder.setOutputFile(varPtr.DefaultStorageDir + fileName  + ".mp4");
    recorder.setMaxDuration(50000); // 50 seconds
    //recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}

从我在这里看到的onSurfaceCreated函数调用它

 @Override
public void surfaceCreated(SurfaceHolder holder)
{
    Log.v(LOGTAG, "surfaceCreated");
    initRecorder();

}

我的清单中有这个

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.front" />
<uses-feature android:name="android.hardware.camera.back" />
<uses-feature android:name="android.hardware.microphone"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"></uses-permission>

我甚至尝试过使用这个代码,因为我已经在我的avd设置中选择模拟前后摄像头以便模拟它们。我甚至测试了模拟器的默认相机应用程序和视频和静态相机。

 private Camera openFrontFacingCamera()
{
    int cameraCount = 0;
    Camera cam = null;
    cameraCount = Camera.getNumberOfCameras();
    for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
        Camera.getCameraInfo(camIdx, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            try {
                cam = Camera.open(camIdx);
            } catch (RuntimeException e) {
                Log.e("WTF", "Camera failed to open: " + e.getLocalizedMessage());
            }
        }
    }

    return cam;
}

如果有人有Android帮助经验,请!我真的开始绝对鄙视Android的开发。

1 个答案:

答案 0 :(得分:0)

即使没有您LogCat和其他代码,我也会尝试。

对我而言,您的recorder似乎尚未初始化。这就是为什么它会在这条线上抛出NPE。

在将recorder设置为CameraObject之前,请务必初始化recorder

因为关于docs

RuntimeException if opening the camera fails (for example, if the camera is in use by another process or device policy manager has disabled the camera).

所以您的camera-object应该有效...所以唯一的逻辑回答是您的recorder未初始化。

在这里阅读更多内容: http://developer.android.com/reference/android/hardware/Camera.html#open(int)

希望它有所帮助!