Android MediaRecorder

MediaRecorder recorder;
Camera camera;
SurfaceView preview;
SurfaceHolder holder;
boolean isRecording = false;
String TAG = "Evolution Camera";
int frameRate = 30;

public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    setContentView(R.layout.camera_view);

    preview = (SurfaceView) findViewById(R.id.camera_preview);

 // Add a listener to the Capture button
    ImageButton captureButton = (ImageButton) findViewById(R.id.btn_capture);
    captureButton.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                record();
            }
        }
    );
}
private boolean prepareVideoRecorder(){

    camera = getCameraInstance();

    recorder = new MediaRecorder();

    // Step 1: Unlock and set camera to MediaRecorder
    camera.unlock();
    recorder.setCamera(camera);

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

    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

    recorder.setVideoFrameRate(frameRate);

    // Step 4: Set output file
    recorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());

    // Step 5: Set the preview output
    recorder.setPreviewDisplay(preview .getHolder().getSurface());

    // Step 6: Prepare configured MediaRecorder
    try {
        recorder.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;
    }
    return true;
}

void record()
{

    if (isRecording) {
        // stop recording and release camera
        recorder.stop();  // stop the recording
        releaseMediaRecorder(); // release the MediaRecorder object
        camera.lock();         // take camera access back from MediaRecorder

        // inform the user that recording has stopped
        //setCaptureButtonText("Capture");
        isRecording = false;
    } else {
        // initialize video camera
        if (prepareVideoRecorder()) {
            // Camera is available and unlocked, MediaRecorder is prepared,
            // now you can start recording
            recorder.start();
            setParameters();

            // inform the user that recording has started
            //setCaptureButtonText("Stop");
            isRecording = true;
        } else {
            // prepare didn't work, release the camera
            releaseMediaRecorder();
            // inform user
        }
    }
}

void setParameters()
{
// set Camera parameters
   Camera.Parameters params = camera.getParameters();

   if (params.getMaxNumMeteringAreas() > 0){ // check that metering areas are supported
       List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>();

       Rect areaRect1 = new Rect(-100, -100, 100, 100);    // specify an area in center of image
       meteringAreas.add(new Camera.Area(areaRect1, 600)); // set weight to 60%
       Rect areaRect2 = new Rect(800, -1000, 1000, -800);  // specify an area in upper right of image
       meteringAreas.add(new Camera.Area(areaRect2, 400)); // set weight to 40%
       params.setMeteringAreas(meteringAreas);

   }
   params.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);

   camera.setParameters(params);
}

    @Override
    protected void onPause() {
        super.onPause();
        if (isRecording) {
            recorder.stop();  // stop the recording
            releaseMediaRecorder(); // release the MediaRecorder object
            camera.lock();
            isRecording = false;
        }
        else {

            releaseMediaRecorder();
        }
        releaseCamera();
    }

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

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

/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
      return Uri.fromFile(getOutputMediaFile(type));
}

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_DCIM), "Evolution");
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    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 + ".mp4");
        Log.d("MyCameraApp", "File created "+ mediaStorageDir.getPath().toString());
    } else {
        return null;
    }

    return mediaFile;
}

public static Camera getCameraInstance(){
    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}

@Override
public void onPreviewFrame(byte[] data, Camera camera) {
    // TODO Auto-generated method stub

}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    // TODO Auto-generated method stub

}
@Override
public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub

}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    if (isRecording) {
        recorder.stop();
        isRecording = false;
    }
    recorder.release();

}

Android MediaRecorder

时间: 2024-10-10 19:22:52

Android MediaRecorder的相关文章

android MediaRecorder录制音频

使用MediaRecorder录制音频步骤: 创建MediaRecorder对象 调用MediaRecorder的setAudioSource()方法设置声音来源,一般传入MediaRecorder.AudioSource.MIC参数指定录制来自麦克风的声音 调用MediaRecorder对象的setOutputFormat()设置所录制的音频 文件的格式 调用MediaRecorder对象的setAudioEncoder() ,setAudioEncodingBitRate(int bitRa

Android MediaRecorder录音与播放

上一篇讲到了使用意图录音,这篇文章将使用MediaRecorder类来录音,从而提供更多的灵活性. 效果图: 源代码奉上: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" andr

利用 android mediaRecorder c++类进行视频编码

本例中media source为camera.(学习的平台是android sdk6.0) 调用关系图: startRecording: recorder = New MediaRecorder(String16()); classMediaRecorder : public BnMediaRecorderClient, public virtualIMediaDeathNotifier 在创建mediaRecorder的时侯,我们先获取IMediaPlayerService指针,然后再创建IM

Android MediaRecorder实现暂停断点录音功能

基本原理如下:MediaRecorder通过MIC录音,系统没有自带的pause功能,每次暂停录音,都会结束本次的录音.现在本人的设计思路是:MediaRecorder录音暂停时,保存这段所录下的音频A,继续录音后,再次暂停,保留录音音频B:以此类推直到最终的录音结束时,依次读取之前保存的A.B……的录音文件,并将其合并在一起.涉及的技术:文件的保存读取.音频的合并等 音频的合并:设置MediaRecorder的音频输出格式mMediaRecorder01.setOutputFormat(Med

android MediaRecorder start failed:-38【转】

本文转载自:http://blog.csdn.net/fnuwfnh/article/details/46698509 最近在学习android 录音方面的知识,发现在部分手机正常运行的APP,在华为平板上挂了,eclipse的Logcat显示MediaRecorder start failed:-38.查了下资料,原因是我的APP在编码时使用了多路录音,而调试用的华为平板在硬件上只能单路录音,不支持多路录音.目前mtk的75,15,77,17平台硬件上只支持单路录音,不支持多路录音,后续89平

Android: MediaRecorder start failed

在某些机型上,MediaRecorder在调用start方法时,会出现start failed的错误,有一种可能是setVideoFrameRate导致的.要解决这个问题,只需要注释掉这条语句就可以了. mediaRecorder.setVideoFrameRate(16);

Android MediaRecorder录制视频提示start failed的解决办法

转自https://blog.csdn.net/w815878564/article/details/49247411 今天测试MediaRecorder录制功能的时候出现一个蛋疼的BUG,按照官方提供的示例写好之后,start居然报错,打印日志一看说:start failed. 代码如下: [java] view plain copy mCamera = Camera.open(0); surfaceView = new SurfaceView(this); setContentView(su

Android录音--AudioRecord、MediaRecorder

Android提供了两个API用于实现录音功能:android.media.AudioRecord.android.media.MediaRecorder. 网上有很多谈论这两个类的资料.现在大致总结下: 1.AudioRecord 主要是实现边录边播(AudioRecord+AudioTrack)以及对音频的实时处理(如会说话的汤姆猫.语音) 优点:语音的实时处理,可以用代码实现各种音频的封装 缺点:输出是PCM语音数据,如果保存成音频文件,是不能够被播放器播放的,所以必须先写代码实现数据编码

Android(java)学习笔记144:Android音视频录制类MediaRecorder用法举例

Android语音录制可以通过MediaRecorder和AudioRecorder.MediaRecorder本来是多媒体录制控件,可以同时录制视频和语音,当不指定视频源时就只录制语音(默认录制语言):AudioRecorder只能录制语音.二者录制的区别在于,MediaRecorder固定了语音的编码格式,具体平台支持类型可以在http://developer.android.com/guide/appendix/media-formats.html这里查看,而且使用时指定输出文件,在录制的