使用surfaceHolder时如何从后视图更改摄像机视图

时间:2015-02-03 13:19:49

标签: android camera

我尝试了很多例子,但我没有得到任何输出。 请告诉我将摄像机视图从后到前,从前到后更改。我不知道怎么做这件事。

My Codings如下所示

我的VideoActivity

public class VideoView extends Activity implements OnClickListener {
    private Camera cameraObject;
    private MyCameraSurfaceView myCameraSurfaceView;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
    private static final String IMAGE_DIRECTORY_NAME = "VideoView";
    protected static final String TAG = null;

    public static final int MEDIA_TYPE_VIDEO = 2;
    static Uri fileUri;
    SurfaceHolder surfaceHolder;
    static String picture, video, timestamp, Title;
    static String play = "video";
    private static int RESULT_LOAD_IMAGE = 1;
    private MediaRecorder mMediaRecorder;
    boolean isRecording;
    static ArrayList<String> userlist;
    Context context;
    private long startTime = 0L;

    private Handler customHandler = new Handler();;

    long timeInMilliseconds = 0L;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;

    TextView clicked, gallary, takephoto, camerafront, cameraback, videoview,
            audioview, tbtn, capturecamera, timerValue, cam;
    FrameLayout preview;
    RatingBar ratings;
    AlertDialog.Builder builder1;
    private Runnable updateTimerThread = new Runnable() {

        public void run() {

            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            secs = secs % 60;
            int milliseconds = (int) (updatedTime % 1000);
            timerValue.setText("" + mins + ":" + String.format("%02d", secs)
                    + ":" + String.format("%03d", milliseconds));
            customHandler.postDelayed(this, 0);
        }

    };

    static boolean val = false;

    public static Camera isCameraAvailiable() {
        Camera object = null;
        try {

            object = Camera.open();// default back facing camera
            System.out.println("Camera object default back facing camera");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Camera object");
        }
        return object;
    }

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isRecording = false;
        setContentView(R.layout.activity_video_view);
        cameraObject = isCameraAvailiable();
        preview = (FrameLayout) findViewById(R.id.imageview);
        clicked = (TextView) findViewById(R.id.done);
        gallary = (TextView) findViewById(R.id.image);
        capturecamera = (TextView) findViewById(R.id.camera);
        camerafront = (TextView) findViewById(R.id.fonrt);
        cameraback = (TextView) findViewById(R.id.back);
        videoview = (TextView) findViewById(R.id.video);
        audioview = (TextView) findViewById(R.id.audio);
        tbtn = (TextView) findViewById(R.id.t);
        ratings = (RatingBar) findViewById(R.id.ratingBar1);
        timerValue = (TextView) findViewById(R.id.timerValue);
        cam = (TextView) findViewById(R.id.flipcam);
        // cameraObject = isCameraAvailiable();
        // mMediaRecorder = new MediaRecorder();

        myCameraSurfaceView = new MyCameraSurfaceView(this, cameraObject);
        // showCamera = new ShowCamera(this, cameraObject);

        preview.addView(myCameraSurfaceView);
        tbtn.setOnClickListener(this);
        userlist = new ArrayList<String>();
        // showCamera = new ShowCamera(this, cameraObject);

        // preview.addView(showCamera);
        videoview.setOnClickListener(this);
        capturecamera.setOnClickListener(this);
        cam.setOnClickListener(this);

    }

    @SuppressLint("NewApi") @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        switch (arg0.getId()) {

        case R.id.video:
            System.out.println("video ### prepareVideoRecorder***");
            if (isRecording) {
                // stop recording and release camera
                mMediaRecorder.stop();
                timeSwapBuff += timeInMilliseconds;
                customHandler.removeCallbacks(updateTimerThread);// stop the
                                                                    // recording
                releaseMediaRecorder(); // release the MediaRecorder object
                // cameraObject.lock(); // take camera access back from
                // MediaRecorder
                System.out.println("-----isRecording----");
                // inform the user that recording has stopped
                // setText("Capture");
                Toast.makeText(getApplicationContext(), "Capture",
                        Toast.LENGTH_SHORT).show();
                isRecording = false;
            } else {
                // initialize video camera
                releaseCamera();
                if (!prepareVideoRecorder()) {
                    // Camera is available and unlocked, MediaRecorder is
                    // prepared,
                    // now you can start recording

                    finish();
                    System.out
                            .println(" ### if (prepareVideoRecorder()now you can start recording)***");

                    // inform the user that recording has started
                    // setCaptureButtonText("Stop");
                    Toast.makeText(getApplicationContext(), "Stop",
                            Toast.LENGTH_SHORT).show();
                    isRecording = true;
                    System.out.println("-----prepareVideoRecorder----");
                } /*
                 * else { // prepare didn't work, release the camera
                 * releaseMediaRecorder();
                 */
                mMediaRecorder.start();
                startTime = SystemClock.uptimeMillis();
                customHandler.postDelayed(updateTimerThread, 0);
                isRecording = true;
                // videoview.setText("STOP");
                Toast.makeText(getApplicationContext(), "recording started",
                        Toast.LENGTH_SHORT).show();
                System.out.println("----- mMediaRecorder.start();----");
                // inform user
            }
        case R.id.flipcam: {

            try {
                cameraObject.stopPreview();
                preview.removeView(myCameraSurfaceView);
                cameraObject.release();
                cameraObject = Camera.open(1);

                myCameraSurfaceView = new MyCameraSurfaceView(VideoView.this,
                        cameraObject);

                preview.addView(myCameraSurfaceView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        default:
            break;
        }
    }



    /** A safe way to get an instance of the Camera object. */

    private boolean prepareVideoRecorder() {

        System.out.println(" ###method prepareVideoRecorder***");
        cameraObject = isCameraAvailiable();
        mMediaRecorder = new MediaRecorder();
        cameraObject.unlock();
        mMediaRecorder.setCamera(cameraObject);

        // Step 2: Set sources
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        System.out.println("Step 2: Set sources");

        // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
        mMediaRecorder.setProfile(CamcorderProfile
                .get(CamcorderProfile.QUALITY_HIGH));
        // mMediaRecorder.setOutputFile("/sdcard/Pictures/BusinessCard/BusinessCard.mp4");
        System.out
                .println("Step 3: Set a CamcorderProfile (requires API Level 8 or higher)");

        // Step 4: Set output file
        mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO)
                .toString());
        System.out.println("Step 4: Set output file");

        // Step 5: Set the preview output
        mMediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder()
                .getSurface());
        System.out.println("Step 5: Set the preview output");

        // Step 6: Prepare configured MediaRecorder
        System.out.println("Step 6: Prepare configured MediaRecorder");

        try {
            mMediaRecorder.prepare();
            System.out.println("mMediaRecorder.prepare");
        } catch (IllegalStateException e) {
            Log.d(TAG,
                    "IllegalStateException preparing MediaRecorder: "
                            + e.getMessage());
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
        }
        System.out.println("return true in prepareVideoRecorder");
        return true;
    }

    private static File getOutputMediaFile(int type) {
        // TODO Auto-generated method stub
        File mediastoredir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                IMAGE_DIRECTORY_NAME);
        System.out.println(" ### Environment.DIRECTORY_DCIM" + " " + " "
                + Environment.DIRECTORY_PICTURES);
        if (!mediastoredir.exists()) {
            if (!mediastoredir.mkdir()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }
        timestamp = new SimpleDateFormat("yyyyMMdd HHmmss", Locale.getDefault())
                .format(new java.util.Date());
        timestamp.split("");
        System.out.println(" ### split" + timestamp);
        File mediafile;
        if (type == MEDIA_TYPE_VIDEO) {
            mediafile = new File(mediastoredir.getPath() + File.separator
                    + "VID_" + timestamp + ".mp4");
            System.out.println(" Video path " + mediastoredir.getPath()
                    + File.separator + "VID_" + timestamp + ".mp4");
            // video path
            video = mediastoredir.getPath() + File.separator + "VID_"
                    + timestamp + ".mp4";

            /*
             * m.setsavepath(video); m.setobjecttype(play);
             * c.setdatetime(timestamp); m.setdatetime(timestamp);
             * //helper.adddetail(m);
             */
            System.out.println(" ### IMAGE" + video);
            System.out.println(" mediastoredir.getPath()"
                    + mediastoredir.getPath());
            System.out.println(" mediafile)" + mediafile);
            System.out.println(" ### timestamp***" + timestamp);

        } else {
            return null;
        }
        return mediafile;
    }

    /*
     * @Override protected void onActivityResult(int requestCode, int
     * resultCode, Intent data) { if (requestCode ==
     * CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { //
     * Image captured and saved to fileUri specified in the Intent
     * Toast.makeText(this, "Image saved to:\n" + data.getData(),
     * Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { //
     * User cancelled the image capture } else { // Image capture failed, advise
     * user } }
     * 
     * if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) { if (resultCode
     * == RESULT_OK) { // Video captured and saved to fileUri specified in the
     * Intent Toast.makeText(this, "Video saved to:\n" + data.getData(),
     * Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { //
     * User cancelled the video capture } else { // Video capture failed, advise
     * user } } }
     */

    /*
     * @Override protected void onResume() { super.onResume(); if (cameraObject
     * == null) { cameraObject = isCameraAvailiable();
     * 
     * // Step 1: Unlock and set camera to MediaRecorder System.out
     * .println("onResume()----Step 1: Unlock and set camera to MediaRecorder;"
     * ); mMediaRecorder.setCamera(cameraObject);
     * System.out.println("onResume()----isCameraAvailiable();"); }
     * 
     * if (showCamera == null) {
     * System.out.println("cameraObject = isCameraAvailiable();"); showCamera =
     * new ShowCamera(this, cameraObject);
     * 
     * preview.addView(showCamera);
     * 
     * System.out.println("onResume()----preview.addView(showCamera);"); }
     * Toast.makeText(getApplicationContext(), "onResume()",
     * Toast.LENGTH_SHORT).show(); }
     */

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder(); // if you are using MediaRecorder, release it
                                // first
        releaseCamera(); // release the camera immediately on pause event
    }

    private void releaseCamera() {
        if (cameraObject != null) {
            cameraObject.release(); // release the camera for other applications
            cameraObject = null;
        }
    }

    private void releaseMediaRecorder() {
        if (mMediaRecorder != null) {
            mMediaRecorder.reset(); // clear recorder configuration
            mMediaRecorder.release(); // release the recorder object
            mMediaRecorder = null;
            cameraObject.lock(); // lock camera for later use
        }
    }

    public class MyCameraSurfaceView extends SurfaceView implements
            SurfaceHolder.Callback {

        private SurfaceHolder mHolder;
        private Camera mCamera;

        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;

            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format,
                int weight, int height) {
            // If your preview can change or rotate, take care of those events
            // here.
            // Make sure to stop the preview before resizing or reformatting it.

            if (mHolder.getSurface() == null) {
                // preview surface does not exist
                return;
            }

            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e) {
                // ignore: tried to stop a non-existent preview
            }

            // make any resize, rotate or reformatting changes here

            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e) {
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            // The Surface has been created, now tell the camera where to draw
            // the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-gene`enter code here`rated method stub

        }

    }
}
Here in flipcam i have change my camera view`enter code here`

0 个答案:

没有答案