欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

camera demo

程序员文章站 2022-05-08 22:35:15
...

package com.keda.xh_testcamera;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

//import com.example.mycamera.R.id;

@SuppressLint(“NewApi”)
public class MainActivity extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
private Camera mCamera;
private CameraPreview mPreview;
private MediaRecorder mMediaRecorder; // 录制视频的类
private boolean isRecording = false;
private TextureCameraPreview.OnStartVideoListener onStartVideoListener;
private static final String TAG = “ERROR”;
private PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: "
+ “e.getMessage()”);
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);
    // 创建Camera实例
    mCamera = getCameraInstance();
    //调整预览方向
    mCamera.setDisplayOrientation(90);
    //
    Camera.Parameters params = mCamera.getParameters();
    params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    mCamera.setParameters(params);
    // 创建Preview view并将其设为activity中的内容
    mPreview = new CameraPreview(this, mCamera);
    mPreview.setSurfaceTextureListener(mPreview);
    //设置浑浊
    mPreview.setAlpha(0.5f);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    // preview.setAlpha(0.0f);
    preview.addView(mPreview);
    Button captureButton = (Button) findViewById(R.id.TakePicture);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 从摄像头获取图片
            mCamera.takePicture(null, null, mPicture);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mCamera.startPreview();
        }
    });
    //开始录像
    Button startButton = (Button) findViewById(R.id.StartRecord);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isRecording) {
                startRecord(getOutputMediaFile(MEDIA_TYPE_VIDEO), new TextureCameraPreview.OnStartVideoListener() {
                    @Override
                    public void onStart() {
                        // TODO: 开始录像时的回调
                    }

                    @Override
                    public void onStop() {
                        // TODO: 录像结束时的回调
                    }
                });
            }
        }
    });

    //结束录像
    Button stopButton = (Button) findViewById(R.id.StopRecorder);
    stopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopRecord();
        }
    });
}

/** 安全获取Camera对象实例的方法 */

public static Camera getCameraInstance() {
    Camera c = null;
    try {
        c = Camera.open(); // 试图获取Camera实例
    }
    catch (Exception e) {
        // 摄像头不可用(正被占用或不存在)
    }
    return c; // 不可用则返回null
}


/** 为保存图片或视频创建File */
private static File getOutputMediaFile(int type) {
    // 安全起见,在使用前应该
    // 用Environment.getExternalStorageState()检查SD卡是否已装入
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    // 如果期望图片在应用程序卸载后还存在、且能被其它应用程序共享,
    // 则此保存位置最合适
    // 如果不存在的话,则创建存储目录
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
        Log.d("MyCameraApp", "failed to create directory");
    }
    // 创建媒体文件名
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".3gp");
    } else {
        return null;
    }
    return mediaFile;
}

// ---------------- 录像
/*init Mediarecorder*/
private boolean initMediaRecorder(File outputfile) {
    mMediaRecorder = new MediaRecorder();
    if (mCamera != null) {
        // 解锁并将相机设置daoMediaRecorder
        mCamera.unlock();
        mMediaRecorder.setCamera(mCamera);
        // 设置资源
        //mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        //视频旋转90度
        mMediaRecorder.setOrientationHint(90);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        // 设置CamcorderProfile(需要API级别8或更高版本)
       // mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        // 设置录制的视频编码h263 h264
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        // 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错
        mMediaRecorder.setVideoSize(4632, 3480);
        //较为清晰,且文件大小为2M(1秒)
        mMediaRecorder.setVideoEncodingBitRate(4*1024*1024);
        // 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错
        mMediaRecorder.setVideoFrameRate(30);
        //mMediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        // 设置输出文件
        mMediaRecorder.setOutputFile(outputfile.getPath());
        // 准备配置的MediaRecorder
        try {
            mMediaRecorder.prepare();
            Toast.makeText(this, "开始录像", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "录像配置准备失败", Toast.LENGTH_SHORT).show();
            mMediaRecorder.release();
            return false;
        }
        return true;
    }
    Toast.makeText(this, "mCamera = null", Toast.LENGTH_SHORT).show();
    return false;
}

/*release MediaRecorder*/
private void releaseMediaRecorder() {
    if (mMediaRecorder != null) {
        mMediaRecorder.reset();
        mMediaRecorder.release();
        mMediaRecorder = null;
    }
}

/**/
public void startRecord(File outputfile, TextureCameraPreview.OnStartVideoListener listener) {
    this.onStartVideoListener = listener;
    if (initMediaRecorder(outputfile)) {
        new MediaPrepareTask(listener).execute();
    } else {
        Toast.makeText(this, "开始录制视频失败", Toast.LENGTH_SHORT).show();
    }
}

/*stop Record*/
public void stopRecord() {
    if (isRecording) {
        Toast.makeText(this, "结束录像", Toast.LENGTH_SHORT).show();
        mMediaRecorder.stop();
        releaseMediaRecorder();
        mCamera.lock();
        if (onStartVideoListener != null)
            onStartVideoListener.onStop();
    } else {
        releaseMediaRecorder();
    }
    isRecording = false;
}

/*class mediaprepare*/
class MediaPrepareTask extends AsyncTask<Void, Void, Boolean> {

    TextureCameraPreview.OnStartVideoListener listener;

    MediaPrepareTask(TextureCameraPreview.OnStartVideoListener listener) {
        this.listener = listener;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        mMediaRecorder.start();
        isRecording = true;
        return true;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if (listener != null)
            listener.onStart();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // 捕获的图像保存到Intent指定的fileUri
            Toast.makeText(this, "Image saved to:\n" + data.getData(),
                    Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            // 用户取消了图像捕获
        } else {
            // 图像捕获失败,提示用户
        }
    }

    if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // 捕获的视频保存到Intent指定的fileUri
            Toast.makeText(this, "Video saved to:\n" + data.getData(),
                    Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            // 用户取消了视频捕获
        } else {
            // 视频捕获失败,提示用户
        }
    }
}


@Override
protected void onPause() {
    super.onPause();
    releaseCamera(); // 在暂停事件中立即释放摄像头
}

private void releaseCamera() {
    if (mCamera != null) {
        mCamera.release(); // 为其它应用释放摄像头
        mCamera = null;
    }
}

}

相关标签: Android Camera