1.Camera

package com.trutalk.rollcall.fragment;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.trutalk.rollcall.R;
import com.trutalk.rollcall.activity.RecordActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystem;


public class PhotoRecordFragment extends Fragment implements View.OnClickListener {
    private final String TAG = "PhotoRecordFragment";

    private RecordActivity mActivity;
    private OnFragmentInteractionListener mListener;
    private SurfaceView mCameraSurfaceView;
    private Preview mPreview;
    private Camera mCamera;
    private SurfaceHolder mHolder;
    private View mTakePicItem;
    private View mOperateItem;
    private View mTakePicBtn;
    private View mDelBtn;
    private View mUploadBtn;
    private int mCameraOrientation = 0;

    public PhotoRecordFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_photo_record, container, false);
        mCameraSurfaceView = (SurfaceView) view.findViewById(R.id.cameraView);
        mTakePicItem = view.findViewById(R.id.take_pic_item);
        mOperateItem = view.findViewById(R.id.operate_btn_item);
        mDelBtn = view.findViewById(R.id.photo_del_btn);
        mDelBtn.setOnClickListener(this);
        mTakePicBtn = view.findViewById(R.id.take_pic_btn);
        mTakePicBtn.setOnClickListener(this);
        mUploadBtn = view.findViewById(R.id.photo_upload_btn);
        mUploadBtn.setOnClickListener(this);
        mPreview = new Preview(mActivity);
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        try {
            mCamera = Camera.open();
            Camera.Parameters parameters = mCamera.getParameters(); // Camera parameters to obtain
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
            mCamera.setParameters(parameters); // Setting camera parameters
            Log.i(TAG, "Camera.open");
        } catch (Exception e) {
            e.printStackTrace();
            if (mCamera != null) {
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            }
        }
        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
        }
        mActivity = (RecordActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.photo_del_btn:
                deletePhoto();
                break;
            case R.id.take_pic_btn:
                takePicture();
                break;
            case R.id.photo_upload_btn:
                mActivity.uploadFile(RecordActivity.PHOTO_RECORD);
                break;
        }

    }

    private void deletePhoto() {
        try {
            File recordFile = new File(Environment.getExternalStorageDirectory() + File.separator + "photo.jpg");
            if (recordFile.exists()) {
                recordFile.delete();
            }

            mCamera.startPreview();
            mOperateItem.setVisibility(View.GONE);
            mTakePicItem.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void takePicture() {
        try {
            mCamera.takePicture(null, null, null, new Camera.PictureCallback() {

                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                    //imageView.setImageBitmap(bitmap);
                    mTakePicItem.setVisibility(View.GONE);
                    mOperateItem.setVisibility(View.VISIBLE);
                    String path = savePhoto(data);
                    if ("NOSPACE".equals(path)) {
                        Toast.makeText(mActivity, R.string.space_exception, Toast.LENGTH_SHORT).show();
                    }
                    int degree = readPictureDegree(path);
                    if (degree != mCameraOrientation && mCameraOrientation == 90) {
                        setPictureDegree90(path);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String savePhoto(byte[] data) {
        String path = Environment.getExternalStorageDirectory() + File.separator + "photo.jpg";
        try {
            //判断是否装有SD卡
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //判断SD卡上是否有足够的空间
                String storage = Environment.getExternalStorageDirectory().toString();
                StatFs fs = new StatFs(storage);
                long available = fs.getAvailableBlocks() * fs.getBlockSize();
                if (available < data.length) {
                    //空间不足直接返回空
                    return "NOSPACE";
                }
                File file = new File(path);
                if (!file.exists())
                    //创建文件
                    file.createNewFile();
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(data);
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return path;
    }

    private int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);

            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                default:
                    degree = 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    private void setPictureDegree90(String path) {
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            //修正图片的旋转角度,设置其不旋转。这里也可以设置其旋转的角度,可以传值过去,
            //例如旋转90度,传值ExifInterface.ORIENTATION_ROTATE_90,需要将这个值转换为String类型的
            exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, "6");
            exifInterface.saveAttributes();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    class Preview extends ViewGroup implements Camera.PreviewCallback, SurfaceHolder.Callback {

        Preview(Context context) {
            super(context);
            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = mCameraSurfaceView.getHolder();
            mHolder.addCallback(this);
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
        }

        public void setCameraDisplayOrientation(Activity activity,
                                                int cameraId, android.hardware.Camera camera) {
            android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
            android.hardware.Camera.getCameraInfo(cameraId, info);
            int rotation = activity.getWindowManager().getDefaultDisplay()
                    .getRotation();
            int degrees = 0;
            switch (rotation) {
                case Surface.ROTATION_0:
                    degrees = 0;
                    break;
                case Surface.ROTATION_90:
                    degrees = 90;
                    break;
                case Surface.ROTATION_180:
                    degrees = 180;
                    break;
                case Surface.ROTATION_270:
                    degrees = 270;
                    break;
            }

            int result;
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                result = (info.orientation + degrees) % 360;
                result = (360 - result) % 360; // compensate the mirror
            } else { // back-facing
                result = (info.orientation - degrees + 360) % 360;
            }
            mCameraOrientation = result;
            camera.setDisplayOrientation(result);
        }

        public void surfaceCreated(SurfaceHolder holder) {
            Log.i(TAG, "surfaceCreated");
            try {
                if (mCamera != null) {
                    setCameraDisplayOrientation(mActivity, 0, mCamera);
                    mCamera.setPreviewDisplay(holder);
                    Log.i(TAG, "setPreviewDisplay");
                }
            } catch (IOException exception) {
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // Surface will be destroyed when we return, so stop the preview.
            if (mCamera != null) {
                mCamera.stopPreview();
                Log.i(TAG, "stopPreview");
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int w,
                                   int h) {
            mCamera.startPreview();
            Log.i(TAG, "startPreview");
        }

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {

        }

    }
}

2.Video

package com.trutalk.rollcall.fragment;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.CamcorderProfile;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.trutalk.rollcall.R;
import com.trutalk.rollcall.activity.RecordActivity;

import java.io.File;
import java.io.IOException;

import static com.trutalk.rollcall.activity.RecordActivity.VIDEO_RECORD;


public class VideoRecordFragment extends Fragment implements View.OnClickListener {
    private final String TAG = "VideoRecordFragment";
    private OnFragmentInteractionListener mListener;
    private RecordActivity mActivity;
    private View mRecordBtnItem;
    private View mOperateBtnItem;
    private View mDelBtn;
    private View mUploadBtn;
    private TextView mBtnTitle;
    private ImageView mBtnImage;
    private ImageView mBtnPlayImage;
    private Preview mPreview;
    private Camera mCamera;
    private MediaRecorder mMediaRecorder;
    private SurfaceView mCameraSurfaceView;
    private SurfaceView mVideoSurfaceView;
    private SurfaceHolder mHolder;
    private int mCameraOrientation = 0;
    private boolean mIsRecording = false;
    private boolean mIsPlaying = false;
    private boolean mIsVideoSurfaceCreated = false;


    private MediaPlayer mMediaPlayer;

    public VideoRecordFragment() {
        // Required empty public constructor
    }

    public static VideoRecordFragment newInstance(String param1, String param2) {
        VideoRecordFragment fragment = new VideoRecordFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_video_record, container, false);
        mBtnTitle = (TextView) view.findViewById(R.id.record_btn_title);
        mCameraSurfaceView = (SurfaceView) view.findViewById(R.id.cameraView);
        mVideoSurfaceView = view.findViewById(R.id.videoView);
        mRecordBtnItem = view.findViewById(R.id.record_btn_item);
        mOperateBtnItem = view.findViewById(R.id.operate_btn_item);
        mBtnImage = view.findViewById(R.id.record_btn_icon);
        mBtnTitle = view.findViewById(R.id.record_btn_title);
        mBtnImage.setOnClickListener(this);
        mDelBtn = view.findViewById(R.id.video_del_btn);
        mDelBtn.setOnClickListener(this);
        mBtnPlayImage = view.findViewById(R.id.video_play_btn);
        mBtnPlayImage.setOnClickListener(this);
        mUploadBtn = view.findViewById(R.id.video_upload_btn);
        mUploadBtn.setOnClickListener(this);
        mPreview = new Preview(mActivity);
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        try {
            mCamera = Camera.open();
            Camera.Parameters parameters = mCamera.getParameters(); // Camera parameters to obtain
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
            mCamera.setParameters(parameters); // Setting camera parameters
            Log.i(TAG, "Camera.open");
        } catch (Exception e) {
            e.printStackTrace();
            if (mCamera != null) {
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            }
        }
        return view;
    }

    private void takeVideo() {
        try {
            mIsRecording = true;
            mBtnTitle.setText(R.string.stop_record);
            mBtnImage.setImageResource(R.drawable.ic_stop);
            if (mMediaRecorder == null) {
                mMediaRecorder = new MediaRecorder();
            }
            mCamera.unlock();
            CamcorderProfile mProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);

            //1st. Initial state
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setCamera(mCamera);

            //2st. Initialized state
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

            //3st. config
            mMediaRecorder.setOutputFormat(mProfile.fileFormat);
            mMediaRecorder.setAudioEncoder(mProfile.audioCodec);
            mMediaRecorder.setVideoEncoder(mProfile.videoCodec);
            mMediaRecorder.setOrientationHint(mCameraOrientation);
            mMediaRecorder.setOutputFile(Environment.getExternalStorageDirectory() + File.separator + "video.3pg");
            mMediaRecorder.setVideoSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight);
            mMediaRecorder.setVideoFrameRate(mProfile.videoFrameRate);
            mMediaRecorder.setVideoEncodingBitRate(mProfile.videoBitRate);
            mMediaRecorder.setAudioEncodingBitRate(mProfile.audioBitRate);
            mMediaRecorder.setAudioChannels(mProfile.audioChannels);
            mMediaRecorder.setAudioSamplingRate(mProfile.audioSampleRate);
            mMediaRecorder.setPreviewDisplay(mHolder.getSurface());

            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopRecordVideo() {
        try {
            mIsRecording = false;
            mRecordBtnItem.setVisibility(View.GONE);
            mOperateBtnItem.setVisibility(View.VISIBLE);
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
            if (mCamera != null) {
                mCamera.stopPreview();
                //mCamera.release();
                //mCamera = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
        }
        mActivity = (RecordActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        mListener = null;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.record_btn_icon:
                if (mIsRecording) {
                    stopRecordVideo();
                } else {
                    takeVideo();
                }
                break;
            case R.id.video_del_btn:
                deleteRecord();
                break;
            case R.id.video_play_btn:
                if (mIsPlaying) {
                    stopRecord();
                } else {
                    playRecord();
                }
                break;
            case R.id.video_upload_btn:
                mActivity.uploadFile(VIDEO_RECORD);
                break;
        }
    }

    private void deleteRecord() {
        try {
        File recordFile = new File(Environment.getExternalStorageDirectory() + File.separator + "video.3gp");
        if (recordFile.exists()) {
            recordFile.delete();
        }

        mCameraSurfaceView.setVisibility(View.VISIBLE);
        mVideoSurfaceView.setVisibility(View.GONE);
        mCamera.startPreview();
        mOperateBtnItem.setVisibility(View.GONE);
        mRecordBtnItem.setVisibility(View.VISIBLE);
        mBtnImage.setImageResource(R.drawable.ic_start);
        mBtnTitle.setText(R.string.start_record_title);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void playRecord() {
        try {
            if (mMediaPlayer == null) {
                mMediaPlayer = new MediaPlayer();
            }
            mIsPlaying = true;
            mDelBtn.setVisibility(View.INVISIBLE);
            mUploadBtn.setVisibility(View.INVISIBLE);
            mBtnPlayImage.setImageResource(R.drawable.ic_video_stop);
            mMediaPlayer.reset();
            if ((new File(Environment.getExternalStorageDirectory() + File.separator + "video.3pg").exists())) {
                mMediaPlayer.setDataSource(Environment.getExternalStorageDirectory() + File.separator + "video.3pg");
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        Log.d(TAG, "onCompletion");
                        mIsPlaying = false;
                        mDelBtn.setVisibility(View.VISIBLE);
                        mUploadBtn.setVisibility(View.VISIBLE);
                        mBtnPlayImage.setImageResource(R.drawable.ic_video_play);
                    }
                });
                mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        Log.e(TAG, "onError = "+ what);
                        return false;
                    }
                });
                mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        Log.d(TAG, "onPrepared");
                    }
                });
                mMediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {

                    @Override
                    public void onSeekComplete(MediaPlayer mp) {
                        Log.d(TAG, "onSeekComplete");
                    }
                });
                if (mIsVideoSurfaceCreated) {
                    play();
                } else {
                    mCameraSurfaceView.setVisibility(View.GONE);
                    mVideoSurfaceView.setVisibility(View.VISIBLE);
                    //mVideoSurfaceView.setRotation(90);
                    //mVideoSurfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
                    mVideoSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
                        @Override
                        public void surfaceDestroyed(SurfaceHolder holder) {
                            Log.d(TAG, "surfaceDestroyed");
                        }

                        @Override
                        public void surfaceCreated(SurfaceHolder holder) {
                            Log.d(TAG, "surfaceCreated");
                            mIsVideoSurfaceCreated = true;
                            play();
                        }

                        @Override
                        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                                   int height) {
                            Log.d(TAG, "surfaceChanged");
                        }
                    });
                }
            } else {
                Toast.makeText(mActivity, R.string.file_exception, Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void play() {
        try {
            mMediaPlayer.setDisplay(mVideoSurfaceView.getHolder());
            mMediaPlayer.prepare();
            mMediaPlayer.setLooping(false);
            mMediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopRecord() {
        if (mMediaPlayer != null) {
            mIsPlaying = false;
            mDelBtn.setVisibility(View.VISIBLE);
            mUploadBtn.setVisibility(View.VISIBLE);
            mBtnPlayImage.setImageResource(R.drawable.ic_video_play);
            mMediaPlayer.stop();
        }
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


    class Preview extends ViewGroup implements Camera.PreviewCallback, SurfaceHolder.Callback {

        Preview(Context context) {
            super(context);
            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = mCameraSurfaceView.getHolder();
            mHolder.addCallback(this);
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
        }

        public void setCameraDisplayOrientation(Activity activity,
                                                int cameraId, android.hardware.Camera camera) {
            android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
            android.hardware.Camera.getCameraInfo(cameraId, info);
            int rotation = activity.getWindowManager().getDefaultDisplay()
                    .getRotation();
            int degrees = 0;
            switch (rotation) {
                case Surface.ROTATION_0:
                    degrees = 0;
                    break;
                case Surface.ROTATION_90:
                    degrees = 90;
                    break;
                case Surface.ROTATION_180:
                    degrees = 180;
                    break;
                case Surface.ROTATION_270:
                    degrees = 270;
                    break;
            }

            int result;
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                result = (info.orientation + degrees) % 360;
                result = (360 - result) % 360; // compensate the mirror
            } else { // back-facing
                result = (info.orientation - degrees + 360) % 360;
            }
            mCameraOrientation = result;
            camera.setDisplayOrientation(result);
        }

        public void surfaceCreated(SurfaceHolder holder) {
            Log.i(TAG, "surfaceCreated");
            try {
                if (mCamera != null) {
                    setCameraDisplayOrientation(mActivity, 0, mCamera);
                    mCamera.setPreviewDisplay(holder);
                    Log.i(TAG, "setPreviewDisplay");
                }
            } catch (IOException exception) {
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // Surface will be destroyed when we return, so stop the preview.
            if (mCamera != null) {
                mCamera.stopPreview();
                Log.i(TAG, "stopPreview");
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int w,
                                   int h) {
            mCamera.startPreview();
            Log.i(TAG, "startPreview");
        }

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {

        }

    }
}

results matching ""

    No results matching ""