使用自定义相机录制视频时,Android相机为空?

时间:2015-01-27 10:58:00

标签: android camera

我正在使用自定义相机和使用自定义相机录制视频。我正在使用带有viewpager的片段。我在录制视频时遇到一个问题,相机的值不为空,但是当我切换我的活动时,& #34; 屏幕变黑,摄像机的值为空"。我在15天内填写此问题。并且没有得到任何正确的解决方案。我看到了很多答案和链接堆栈溢出,但这不是给我满意的解决方案。我已经完成了以下操作,这是我的代码。

public class Recording_Activity  extends Fragment  implements View.OnTouchListener {
    private AlertDialog dialog;
    private Context mContext;
    private AlertDialog.Builder builder;
    private Context context;
    private LinearLayout layout;
    private FrameLayout myCameraPreview ;
    //private ToggleButton btn_toggle;
    private ImageView btn_record_image,iv_unlock,iv_cross,iv_progress,btn_toggle;
    private Button btn_music,btn_invitefriends,myButton,btn_clock_count;
    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;
    private SurfaceHolder surfaceHolder;
    private boolean recording=false;
    private RelativeLayout harmony_layout,backlayout,record_layout;
    private int check_value;
    private SurfaceHolder mHolder;

    private int temp = 1;
    private  int i=0;
    private int _xDelta,_yDelta;
    private TextView tv_harmony,tv_unlock;
    private File  mFileTemp = null;
    private String workingPath;
    private SharedPreferences sharedPreferences;
    private Editor editor;

    TranslateAnimation animation ;

    private CountDownTimer countDownTimer;
    private boolean timerHasStarted = false;
    private final long startTime = 10 * 1000;
    private final long interval = 1 * 1000;
    private int which;
    private int currentCameraId;
    private boolean inPreview;
    CameraInfo camInfo = new CameraInfo();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.recording_screen, null); 

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        editor = sharedPreferences.edit();
        countDownTimer = new MyCountDownTimer(startTime, interval);
        btn_toggle=(ImageView)root.findViewById(R.id.btn_toggle);
        btn_invitefriends=(Button)root.findViewById(R.id.btn_invitefriends);
        btn_music=(Button)root.findViewById(R.id.btn_music);
        layout=(LinearLayout)root.findViewById(R.id.layout);

        myCameraPreview = (FrameLayout)root.findViewById(R.id.videoview);
        tv_unlock = (TextView)root.findViewById(R.id.tv_unlock);
        //timer = (TextView)root. findViewById(R.id.timer);
        iv_unlock = (ImageView)root.findViewById(R.id.iv_unlock);

        harmony_layout = (RelativeLayout)root.findViewById(R.id.harmony_layout);
        btn_record_image = (ImageView)root.findViewById(R.id.btn_record_image);
        btn_clock_count = (Button)root.findViewById(R.id.btn_clock_count);
        tv_harmony = (TextView)root.findViewById(R.id.tv_harmony);
        iv_cross = (ImageView)root.findViewById(R.id.iv_cross);
        iv_progress= (ImageView)root.findViewById(R.id.iv_progress);
        record_layout = (RelativeLayout)root.findViewById(R.id.recording_layout);
        tv_harmony.getBackground().setAlpha(50);
        btn_toggle.getBackground().setAlpha(80);
        btn_clock_count.setAlpha(50);
        iv_cross.setAlpha(80);
        btn_record_image.setOnTouchListener(this);


        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT ,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin = getResources().getDimensionPixelSize(R.dimen.record_btn_margin_left);
        layoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.record_btn_margin_top);

        btn_record_image.setLayoutParams(layoutParams);

        mContext=getActivity();
        builder=new AlertDialog.Builder(getActivity());

        check_value = sharedPreferences.getInt(PreferenceConstants.VIDEO_CHANCE_REMAINING,3) ;
        tv_unlock.setText(String.valueOf(check_value));


        if (check_value <=0) {
            iv_unlock.setVisibility(View.VISIBLE);
            tv_unlock.setVisibility(View.INVISIBLE);
        }

        iv_unlock.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                LayoutInflater inflater =getActivity().getLayoutInflater();

                View myview = inflater.inflate(R.layout.clock_layout, null);

                builder.setView(myview);
                dialog=builder.create();
                dialog = builder.show();

                ImageView  image = (ImageView)myview.findViewById(R.id.cross);

                ListView list = (ListView)myview.findViewById(R.id.listView1);

                list.setAdapter(new PurchaseListAdapter(getActivity()));
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                            int position, long arg3) {

                    }
                });
                image.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                });

            }
        });
        iv_cross.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),Home.class);
                startActivity(intent);          
            }
        });
        btn_clock_count.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                LayoutInflater inflater =getActivity().getLayoutInflater();

                View myview = inflater.inflate(R.layout.clock_layout, null);

                builder.setView(myview);
                dialog=builder.create();
                dialog = builder.show();

                ImageView  image = (ImageView)myview.findViewById(R.id.cross);

                ListView list = (ListView)myview.findViewById(R.id.listView1);

                list.setAdapter(new PurchaseListAdapter(getActivity()));
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                            int position, long arg3) {}
                });
                image.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                });

            }
        });
        btn_music.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Boolean isLoggedin = sharedPreferences.getBoolean(PreferenceConstants.IS_LOGGED_IN, false);
                if(isLoggedin){
                    PreferenceConstants.obj.setUpView(0);
                }
                else{
                    AlertDialog dialog = Utils.alertDialogWithMessage(getActivity(),getString(R.string.guest_user_cannot_logged_in));
                    dialog.show();
                }
            }
        });
        btn_invitefriends.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Boolean isLoggedin = sharedPreferences.getBoolean(PreferenceConstants.IS_LOGGED_IN, false);
                if(isLoggedin){
                    PreferenceConstants.obj.setUpView(2);
                }
                else{
                    AlertDialog dialog = Utils.alertDialogWithMessage(getActivity(),getString(R.string.guest_user_cannot_logged_in));
                    dialog.show();
                }
            }
        });
        btn_toggle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try{
                    flipcamera();;
                    Log.i("clk", "sucess");
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        });

        this.context = getActivity();

        workingPath = Environment.getExternalStorageDirectory() + "/Scatta";

        myCamera = getCameraInstance();
        if(this.myCamera == null){
            Toast.makeText(getActivity(), 
                    "Fail to get Camera", 
                    Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView = new MyCameraSurfaceView(getActivity(), myCamera);
        myCameraPreview.addView(myCameraSurfaceView);


        return root;
    }
    private void  flipcamera() 
    {
        if (inPreview ) {
            myCamera.stopPreview();
        }
        //NB: if you don't release the current camera before switching, you app will crash
        myCamera.release();

        //swap the id of the camera to be used
        if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
            currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
            myCamera = Camera.open(currentCameraId);
            myCamera.setDisplayOrientation(90);
        }
        else {
            currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
            myCamera = Camera.open();
            myCamera.setDisplayOrientation(90);

        }
        /*  myCamera = Camera.open(currentCameraId);
        myCamera.setDisplayOrientation(90);*/
        try {
            //this step is critical or preview on new camera will no know where to render to
            myCamera.setPreviewDisplay(mHolder);

        } catch (IOException e) {
            e.printStackTrace();
        }
        myCamera.startPreview();
    }

    private Camera getCameraInstance(){
        //  Camera c = null;
        Log.d("No of cameras",Camera.getNumberOfCameras()+"");
        for (currentCameraId = 0; currentCameraId < Camera.getNumberOfCameras(); currentCameraId++) {

            Camera.getCameraInfo(currentCameraId, camInfo);

            if (camInfo.facing==(Camera.CameraInfo.CAMERA_FACING_FRONT )) {
                myCamera = Camera.open(currentCameraId);
                myCamera.setDisplayOrientation(90);
                //  CameraInfo  cameraInfo = new CameraInfo();
                //  int rotation = (cameraInfo.orientation - 180 + 360) % 360;
                Log.d("No of cameras",Camera.CameraInfo.CAMERA_FACING_FRONT+"");

            }

        }
        if (camInfo.facing==(Camera.CameraInfo.CAMERA_FACING_BACK)) {
            try {
                myCamera.release();

                myCamera = Camera.open();
                myCamera.setDisplayOrientation(90);
                Log.d("No of cameras",Camera.CameraInfo.CAMERA_FACING_BACK+"");
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("ecepytion"+e.toString());
            }
        }

        return myCamera;
    }

    private boolean prepareMediaRecorder(){
        myCamera = getCameraInstance();
        mediaRecorder = new MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
        createDir(Environment.getExternalStorageDirectory().toString(), "Scatta");

        mediaRecorder.setOutputFile("/sdcard/Scatta/Scatta" + "temp" + ".mp4");

        mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
        mediaRecorder.setMaxDuration(60000); 
        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());
        mediaRecorder.setOrientationHint(270);



        try {
            mediaRecorder.setPreviewDisplay(mHolder.getSurface());
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }




    private void createDir(String path, String dirName){

        String newFolder = "/" + dirName;
        File myNewFolder = new File(path + newFolder);
        myNewFolder.mkdir();
        mFileTemp = new File(workingPath,newFolder);
    }

    @Override
    public void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();    
        myCameraPreview.removeView(myCameraSurfaceView);// release the camera immediately on pause event
    }
    private void releaseMediaRecorder(){
        if (mediaRecorder != null) {
            mediaRecorder.reset();   // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
            myCamera.lock();           // lock camera for later use
        }
    }

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

    public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

        //private SurfaceHolder mHolder;
        //private Camera mCamera;

        @SuppressWarnings("deprecation")
        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            myCamera = camera;

            mHolder = getHolder();
            mHolder.addCallback(this);
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                int height) {

            if (mHolder.getSurface() == null){
                return;
            }

            try {
                myCamera.setPreviewDisplay(mHolder);
                myCamera.startPreview();
                //  mCamera.unlock();
            } catch (Exception e){
                e.printStackTrace();
                System.out.println("surface changed error"+e);
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                myCamera.setPreviewDisplay(holder);
                myCamera.startPreview();
                //  mCamera.unlock();
            } catch (IOException e){
                e.printStackTrace();
                System.out.println("IOException"+e);
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

            /*mCamera.release();*/

        }
    }


    public static Fragment newInstance(Context _context) {
        Recording_Activity f = new Recording_Activity();    
        return f;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        final int X = (int) event.getRawX();
        final int Y = (int) event.getRawY();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)v.getLayoutParams();
            _xDelta = X- lParams.leftMargin;
            _yDelta = Y- lParams.topMargin;
            System.out.println("_xaDelta value"+_xDelta);
            System.out.println("_yDelta value"+_yDelta);

            if (camInfo.facing==(Camera.CameraInfo.CAMERA_FACING_BACK)) {
                try {
                    myCamera.release();

                    myCamera = Camera.open();
                    myCamera.setDisplayOrientation(90);
                    Log.d("No of cameras",Camera.CameraInfo.CAMERA_FACING_BACK+"");
                    mediaRecorder.start();
                    recording =true;
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("ecepytion"+e.toString());
                }
            }


            /*if(!recording){
                releaseCamera();
                if(!prepareMediaRecorder()){
                    Toast.makeText(getActivity(), 
                            "Wait camera is preparing", 
                            Toast.LENGTH_LONG).show();
                    startActivity(new Intent(getActivity(),FragmentClass.class));

                }
                else{       
                    try {
                        mediaRecorder.start();
                        recording = true;
                        btn_record_image.setBackgroundResource(R.drawable.btn_pressed_icon);
                        PreferenceConstants._mViewPager.setPagingEnabled(false);
                        onAnimate(v);
                        countDownTimer.start();
                        iv_progress.setDrawingCacheEnabled(true);
                        btn_clock_count.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("camera error"+e.toString());
                    }
                }*/

            if (!recording) {
                releaseCamera();
                if (!prepareMediaRecorder()) {
                    Toast.makeText(getActivity(),
                            "Wait camera is preparing", Toast.LENGTH_LONG)
                            .show();
                    startActivity(new Intent(getActivity(),
                            FragmentClass.class));

                } else {
                    try {
                        Log.v("Media Recorder", "Start");
                        Log.v("Camera Info", camInfo.facing + "");
                        /*if (camInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                            mediaRecorder.start();
                            recording = true;
                        }*/
                        mediaRecorder.start();
                        recording = true;
                        btn_record_image
                        .setBackgroundResource(R.drawable.btn_pressed_icon);
                        PreferenceConstants._mViewPager.setPagingEnabled(false);
                        onAnimate(v);
                        countDownTimer.start();
                        iv_progress.setDrawingCacheEnabled(true);
                        btn_clock_count.setGravity(Gravity.CENTER_VERTICAL
                                | Gravity.CENTER_HORIZONTAL);

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("camera error" + e.toString());
                    }
                }
            }

            break;
        case MotionEvent.ACTION_UP:
            File mFile = new File("The output file's absolutePath");
            if(recording){
                try{
                    mediaRecorder.stop();
                    PreferenceConstants._mViewPager.setPagingEnabled(true);
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
                    layoutParams.leftMargin = X - _xDelta;
                    layoutParams.topMargin = Y - _yDelta;
                    layoutParams.rightMargin = -250;
                    layoutParams.bottomMargin = -250;
                    btn_record_image.setLayoutParams(layoutParams);
                    Intent i = new Intent(getActivity(),PlaybackScreen.class);
                    startActivity(i);
                    iv_progress.setDrawingCacheEnabled(false);

                }
                catch(RuntimeException e) {
                    mFile.delete();  //you must delete the outputfile when the recorder stop failed.
                } finally {
                    releaseMediaRecorder();
                    mediaRecorder = null;
                }
                btn_record_image.setBackgroundResource(R.drawable.btn_unpressed_icon);
                recording = false;
                temp++;
                countDownTimer.cancel();
                animation.cancel();
            } 
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            break;
        case MotionEvent.ACTION_POINTER_UP:
            break;
        case MotionEvent.ACTION_MOVE:
            if(check_value > 0)
            {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
                layoutParams.leftMargin = X - _xDelta;
                layoutParams.topMargin = Y - _yDelta;
                layoutParams.rightMargin = -250;
                layoutParams.bottomMargin = -250;
                v.setLayoutParams(layoutParams);
                btn_clock_count.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
            }
            break;
        }
        layout.invalidate();
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        Boolean isLoggedin = sharedPreferences.getBoolean(PreferenceConstants.IS_LOGGED_IN, false);
        if(isLoggedin){
            PreferenceConstants._mViewPager.setPagingEnabled(true);
        }
        else{
            PreferenceConstants._mViewPager.setPagingEnabled(false);
            iv_cross.setVisibility(View.VISIBLE);
        }

    }
    public void onAnimate(View v) {
        animation = new TranslateAnimation(0.0f, 400.0f,
                0.0f, 0.0f);  
        animation.setDuration(8000);  // animation duration 
        iv_progress.startAnimation(animation); 
        animation.setFillAfter(false);

    }

    public class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }


        @Override
        public void onTick(long millisUntilFinished) {
            btn_clock_count.setText("" + millisUntilFinished / 1000);
            btn_clock_count.setGravity(Gravity.CENTER );
        }
        @Override
        public void onFinish() {
            Intent i = new Intent(getActivity(),PlaybackScreen.class);
            startActivity(i);
        }
    }

}

0 个答案:

没有答案