android.media.MediaRecorder#setCamera ( )源码实例Demo

下面列出了android.media.MediaRecorder#setCamera ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: VideoCRE   文件: Camera1Session.java
private Camera1Session(Events events, boolean captureToTexture, Context applicationContext,
    SurfaceTextureHelper surfaceTextureHelper, MediaRecorder mediaRecorder, int cameraId,
    android.hardware.Camera camera, android.hardware.Camera.CameraInfo info,
    CaptureFormat captureFormat, long constructionTimeNs) {
  Logging.d(TAG, "Create new camera1 session on camera " + cameraId);

  this.cameraThreadHandler = new Handler();
  this.events = events;
  this.captureToTexture = captureToTexture;
  this.applicationContext = applicationContext;
  this.surfaceTextureHelper = surfaceTextureHelper;
  this.cameraId = cameraId;
  this.camera = camera;
  this.info = info;
  this.captureFormat = captureFormat;
  this.constructionTimeNs = constructionTimeNs;
  this.activityOrientation = getDeviceOrientation();

  startCapturing();

  if (mediaRecorder != null) {
    camera.unlock();
    mediaRecorder.setCamera(camera);
  }
}
 
源代码2 项目: VideoRecorderTest   文件: MainActivity.java
private boolean prepareMediaRecorder() {
    mMediaRecorder = new MediaRecorder();
    mCamera.unlock();
    mMediaRecorder.setCamera(mCamera);
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P));
    mMediaRecorder.setPreviewDisplay(mHolder.getSurface());
    String path = getSDPath();
    if (path != null) {

        File dir = new File(path + "/VideoRecorderTest");
        if (!dir.exists()) {
            dir.mkdir();
        }
        path = dir + "/" + getDate() + ".mp4";
        mMediaRecorder.setOutputFile(path);
        try {
            mMediaRecorder.prepare();
        } catch (IOException e) {
            releaseMediaRecorder();
            e.printStackTrace();
        }
    }
    return true;
}
 
源代码3 项目: BluetoothCameraAndroid   文件: CameraActivity.java
@Override
public void startRecording(Camera.PreviewCallback previewCallback) {
    recording = true;
    mCamera.unlock();
    mRecordbutton.setBackgroundResource(R.drawable.red_circle_background);
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.setCamera(mCamera);
    mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
    mMediaRecorder.setOutputFile("/sdcard/Video.mp4");
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mMediaRecorder.setOrientationHint(90);
    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

    try {
        mMediaRecorder.prepare();
        mMediaRecorder.start();
        mCamera.startPreview();
        mCamera.setPreviewCallback(previewCallback);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
源代码4 项目: BluetoothCameraAndroid   文件: TestActivity.java
protected void startRecording() throws IOException {
    mMediaRecorder = new MediaRecorder();  // Works well
    mCamera.unlock();

    mMediaRecorder.setCamera(mCamera);

    mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
    mMediaRecorder.setOutputFile("/sdcard/zzzz.mp4");

    mMediaRecorder.prepare();
    mMediaRecorder.start();
}
 
源代码5 项目: FamilyChat   文件: MediaRecorderSystemImpl.java
@Override
public void initRecorder(Camera camera, int cameraId, Surface surface, String filePath)
{
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.reset();
    if (camera != null)
        mMediaRecorder.setCamera(camera);
    mMediaRecorder.setOnErrorListener(this);
    mMediaRecorder.setPreviewDisplay(surface);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频源
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//音频源
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//视频输出格式 也可设为3gp等其他格式
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//音频格式
    mMediaRecorder.setVideoSize(640, 480);//设置分辨率,市面上大多数都支持640*480
    //        mediaRecorder.setVideoFrameRate(25);//设置每秒帧数 这个设置有可能会出问题,有的手机不支持这种帧率就会录制失败,这里使用默认的帧率,当然视频的大小肯定会受影响
    //这里设置可以调整清晰度
    mMediaRecorder.setVideoEncodingBitRate(2 * 1024 * 512);

    if (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK)
        mMediaRecorder.setOrientationHint(90);
    else
        mMediaRecorder.setOrientationHint(270);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//视频录制格式
    mMediaRecorder.setOutputFile(filePath);
}
 
源代码6 项目: NIM_Android_UIKit   文件: CaptureVideoActivity.java
private boolean startRecorderInternal() throws Exception {
    shutdownCamera();
    if (!initCamera()) {
        return false;
    }
    switchCamera.setVisibility(View.GONE);
    mediaRecorder = new MediaRecorder();
    camera.unlock();
    mediaRecorder.setCamera(camera);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    setCamcorderProfile();
    mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
    mediaRecorder.setMaxDuration(1000 * VIDEO_TIMES);
    mediaRecorder.setOutputFile(filename);
    setVideoOrientation();
    mediaRecorder.prepare();
    mediaRecorder.start();
    return true;
}
 
源代码7 项目: Lassi-Android   文件: FullVideoRecorder.java
FullVideoRecorder(@NonNull VideoResult stub, @Nullable VideoRecorder.VideoResultListener listener,
                  @NonNull Camera1 controller, @NonNull Camera camera, int cameraId) {
    super(stub, listener);
    mCamera = camera;
    mController = controller;
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.setCamera(camera);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

    // Get a profile of quality compatible with the chosen size.
    mSize = mResult.getRotation() % 180 != 0 ? mResult.getSize().flip() : mResult.getSize();
    mProfile = CamcorderProfiles.get(cameraId, mSize);
}
 
源代码8 项目: CameraView   文件: JCameraView.java
private void startRecord() {
    mediaRecorder = new MediaRecorder();
    mediaRecorder.reset();
    mCamera.unlock();
    // 设置录制视频源为Camera(相机)
    mediaRecorder.setCamera(mCamera);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    // 设置录制的视频编码h263 h264
    mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    // 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错
    mediaRecorder.setVideoSize(width, height);
    // 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错
    if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) {
        mediaRecorder.setOrientationHint(270);
    } else {
        mediaRecorder.setOrientationHint(90);
    }
    mediaRecorder.setMaxDuration(10000);
    mediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);
    mediaRecorder.setVideoFrameRate(20);
    mediaRecorder.setPreviewDisplay(mHolder.getSurface());
    // 设置视频文件输出的路径
    mediaRecorder.setOutputFile("/sdcard/love.mp4");
    try {
        //准备录制
        mediaRecorder.prepare();
        // 开始录制
        mediaRecorder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
源代码9 项目: VideoCamera   文件: VideoRecorder.java
@SuppressWarnings("deprecation")
protected void configureMediaRecorder(final MediaRecorder recorder, android.hardware.Camera camera) throws IllegalStateException, IllegalArgumentException {
    recorder.setCamera(camera);
    recorder.setAudioSource(mCaptureConfiguration.getAudioSource());
    recorder.setVideoSource(mCaptureConfiguration.getVideoSource());

    CamcorderProfile baseProfile = mCameraWrapper.getBaseRecordingProfile();
    baseProfile.fileFormat = mCaptureConfiguration.getOutputFormat();

    RecordingSize size = mCameraWrapper.getSupportedRecordingSize(mCaptureConfiguration.getVideoWidth(), mCaptureConfiguration.getVideoHeight());
    baseProfile.videoFrameWidth = size.width;
    baseProfile.videoFrameHeight = size.height;
    baseProfile.videoBitRate = mCaptureConfiguration.getVideoBitrate();

    baseProfile.audioCodec = mCaptureConfiguration.getAudioEncoder();
    baseProfile.videoCodec = mCaptureConfiguration.getVideoEncoder();

    recorder.setProfile(baseProfile);
    recorder.setMaxDuration(mCaptureConfiguration.getMaxCaptureDuration());
    recorder.setOutputFile(mVideoFile.getFullPath());
    recorder.setOrientationHint(mCameraWrapper.getRotationCorrection());

    try {
        recorder.setMaxFileSize(mCaptureConfiguration.getMaxCaptureFileSize());
    } catch (IllegalArgumentException e) {
        CLog.e(CLog.RECORDER, "Failed to set max filesize - illegal argument: " + mCaptureConfiguration.getMaxCaptureFileSize());
    } catch (RuntimeException e2) {
        CLog.e(CLog.RECORDER, "Failed to set max filesize - runtime exception");
    }
    recorder.setOnInfoListener(this);
}
 
源代码10 项目: aurora-imui   文件: CameraOld.java
public void setUpMediaRecorder() {
    if (null == mContext) {
        return;
    }
    Activity activity = (Activity) mContext;
    mMediaRecorder = new MediaRecorder();
    mCamera.stopPreview();
    mCamera.unlock();
    mMediaRecorder.setCamera(mCamera);
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mNextVideoAbsolutePath = getVideoFilePath(activity);
    mMediaRecorder.setOutputFile(mNextVideoAbsolutePath);
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setVideoEncodingBitRate(10000000);
    mMediaRecorder.setVideoSize(mPreviewSize.width, mPreviewSize.height);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    switch (getOrientation(mCameraId)) {
        case SENSOR_ORIENTATION_DEFAULT_DEGREES:
            mMediaRecorder.setOrientationHint(ORIENTATIONS.get(rotation));
            break;
        case SENSOR_ORIENTATION_INVERSE_DEGREES:
            mMediaRecorder.setOrientationHint(rotation);
            break;
    }
    try {
        mMediaRecorder.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
源代码11 项目: LandscapeVideoCamera   文件: VideoRecorder.java
@SuppressWarnings("deprecation")
protected void configureMediaRecorder(final MediaRecorder recorder, android.hardware.Camera camera)
        throws IllegalStateException, IllegalArgumentException {
    recorder.setCamera(camera);
    recorder.setAudioSource(mCaptureConfiguration.getAudioSource());
    recorder.setVideoSource(mCaptureConfiguration.getVideoSource());

    CamcorderProfile baseProfile = mCameraWrapper.getBaseRecordingProfile();
    baseProfile.fileFormat = mCaptureConfiguration.getOutputFormat();

    RecordingSize size = mCameraWrapper.getSupportedRecordingSize(mCaptureConfiguration.getVideoWidth(), mCaptureConfiguration.getVideoHeight());
    baseProfile.videoFrameWidth = size.width;
    baseProfile.videoFrameHeight = size.height;
    baseProfile.videoBitRate = mCaptureConfiguration.getVideoBitrate();

    baseProfile.audioCodec = mCaptureConfiguration.getAudioEncoder();
    baseProfile.videoCodec = mCaptureConfiguration.getVideoEncoder();

    recorder.setProfile(baseProfile);
    recorder.setMaxDuration(mCaptureConfiguration.getMaxCaptureDuration());
    recorder.setOutputFile(mVideoFile.getFullPath());
    recorder.setOrientationHint(mCameraWrapper.getRotationCorrection());
    recorder.setVideoFrameRate(mCaptureConfiguration.getVideoFPS());

    try {
        recorder.setMaxFileSize(mCaptureConfiguration.getMaxCaptureFileSize());
    } catch (IllegalArgumentException e) {
        CLog.e(CLog.RECORDER, "Failed to set max filesize - illegal argument: " + mCaptureConfiguration.getMaxCaptureFileSize());
    } catch (RuntimeException e2) {
        CLog.e(CLog.RECORDER, "Failed to set max filesize - runtime exception");
    }
    recorder.setOnInfoListener(this);
}
 
源代码12 项目: In77Camera   文件: CameraEngine.java
private boolean prepareMediaRecorder() {
        try {
           // final Activity activity = getActivity();
            //if (null == activity) return false;
            //final BaseCaptureInterface captureInterface = (BaseCaptureInterface) activity;

           // setCameraDisplayOrientation(mCamera.getParameters());
            mMediaRecorder = new MediaRecorder();
            camera.stopPreview();
            camera.unlock();
            mMediaRecorder.setCamera(camera);

  //          boolean canUseAudio = true;
            //boolean audioEnabled = !mInterface.audioDisabled();
            //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            //    canUseAudio = ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;

//            if (canUseAudio && audioEnabled) {
                mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
//            } else if (audioEnabled) {
//                Toast.makeText(getActivity(), R.string.mcam_no_audio_access, Toast.LENGTH_LONG).show();
//            }
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

            final CamcorderProfile profile = CamcorderProfile.get(currentCameraId, CamcorderProfile.QUALITY_HIGH);
            mMediaRecorder.setOutputFormat(profile.fileFormat);
            mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
            mMediaRecorder.setVideoSize(previewSize.width, previewSize.height);
            mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
            mMediaRecorder.setVideoEncoder(profile.videoCodec);

            mMediaRecorder.setAudioEncodingBitRate(profile.audioBitRate);
            mMediaRecorder.setAudioChannels(profile.audioChannels);
            mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate);
            mMediaRecorder.setAudioEncoder(profile.audioCodec);


            Uri uri = Uri.fromFile(FileUtils.makeTempFile(
                    new File(Environment.getExternalStorageDirectory(),
                            "/Omoshiroi/videos").getAbsolutePath(),
                    "VID_", ".mp4"));

            mMediaRecorder.setOutputFile(uri.getPath());

//            if (captureInterface.maxAllowedFileSize() > 0) {
//                mMediaRecorder.setMaxFileSize(captureInterface.maxAllowedFileSize());
//                mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
//                    @Override
//                    public void onInfo(MediaRecorder mediaRecorder, int what, int extra) {
//                        if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
//                            Toast.makeText(getActivity(), R.string.mcam_file_size_limit_reached, Toast.LENGTH_SHORT).show();
//                            stopRecordingVideo(false);
//                        }
//                    }
//                });
//            }

            mMediaRecorder.setOrientationHint(90);
     //       mMediaRecorder.setPreviewDisplay(mPreviewView.getHolder().getSurface());

            mMediaRecorder.prepare();
            return true;

        } catch (Exception e) {
            camera.lock();
            e.printStackTrace();
            return false;
        }
    }
 
源代码13 项目: Fatigue-Detection   文件: CameraEngine.java
private boolean prepareMediaRecorder() {
        try {
           // final Activity activity = getActivity();
            //if (null == activity) return false;
            //final BaseCaptureInterface captureInterface = (BaseCaptureInterface) activity;

           // setCameraDisplayOrientation(mCamera.getParameters());
            mMediaRecorder = new MediaRecorder();
            camera.stopPreview();
            camera.unlock();
            mMediaRecorder.setCamera(camera);

  //          boolean canUseAudio = true;
            //boolean audioEnabled = !mInterface.audioDisabled();
            //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            //    canUseAudio = ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;

//            if (canUseAudio && audioEnabled) {
                mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
//            } else if (audioEnabled) {
//                Toast.makeText(getActivity(), R.string.mcam_no_audio_access, Toast.LENGTH_LONG).show();
//            }
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

            final CamcorderProfile profile = CamcorderProfile.get(currentCameraId, CamcorderProfile.QUALITY_HIGH);
            mMediaRecorder.setOutputFormat(profile.fileFormat);
            mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
            mMediaRecorder.setVideoSize(previewSize.width, previewSize.height);
            mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
            mMediaRecorder.setVideoEncoder(profile.videoCodec);

            mMediaRecorder.setAudioEncodingBitRate(profile.audioBitRate);
            mMediaRecorder.setAudioChannels(profile.audioChannels);
            mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate);
            mMediaRecorder.setAudioEncoder(profile.audioCodec);


            Uri uri = Uri.fromFile(FileUtils.makeTempFile(
                    new File(Environment.getExternalStorageDirectory(),
                            "/Omoshiroi/videos").getAbsolutePath(),
                    "VID_", ".mp4"));

            mMediaRecorder.setOutputFile(uri.getPath());

//            if (captureInterface.maxAllowedFileSize() > 0) {
//                mMediaRecorder.setMaxFileSize(captureInterface.maxAllowedFileSize());
//                mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
//                    @Override
//                    public void onInfo(MediaRecorder mediaRecorder, int what, int extra) {
//                        if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
//                            Toast.makeText(getActivity(), R.string.mcam_file_size_limit_reached, Toast.LENGTH_SHORT).show();
//                            stopRecordingVideo(false);
//                        }
//                    }
//                });
//            }

            mMediaRecorder.setOrientationHint(90);
     //       mMediaRecorder.setPreviewDisplay(mPreviewView.getHolder().getSurface());

            mMediaRecorder.prepare();
            return true;

        } catch (Exception e) {
            camera.lock();
            e.printStackTrace();
            return false;
        }
    }
 
源代码14 项目: WhatsAppCamera   文件: WhatsappCameraActivity.java
@SuppressLint("SimpleDateFormat")
protected boolean prepareMediaRecorder() throws IOException {

    mediaRecorder = new MediaRecorder(); // Works well
    camera.stopPreview();
    camera.unlock();
    mediaRecorder.setCamera(camera);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    if (flag == 1) {
        mediaRecorder.setProfile(CamcorderProfile.get(1, CamcorderProfile.QUALITY_HIGH));
    } else {
        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
    }
    mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());

    mediaRecorder.setOrientationHint(mOrientation);

    if (Build.MODEL.equalsIgnoreCase("Nexus 6") && flag == 1) {

        if (mOrientation == 90) {
            mediaRecorder.setOrientationHint(mOrientation);
        } else if (mOrientation == 180) {
            mediaRecorder.setOrientationHint(0);
        } else {
            mediaRecorder.setOrientationHint(180);
        }

    } else if (mOrientation == 90 && flag == 1) {
        mediaRecorder.setOrientationHint(270);
    } else if (flag == 1) {
        mediaRecorder.setOrientationHint(mOrientation);
    }
    mediaFileName = "wc_vid_" + System.currentTimeMillis();
    mediaRecorder.setOutputFile(folder.getAbsolutePath() + "/" + mediaFileName + ".mp4"); // Environment.getExternalStorageDirectory()

    mediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {

        public void onInfo(MediaRecorder mr, int what, int extra) {
            // TODO Auto-generated method stub

            if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {

                long downTime = 0;
                long eventTime = 0;
                float x = 0.0f;
                float y = 0.0f;
                int metaState = 0;
                MotionEvent motionEvent = MotionEvent.obtain(
                        downTime,
                        eventTime,
                        MotionEvent.ACTION_UP,
                        0,
                        0,
                        metaState
                );

                imgCapture.dispatchTouchEvent(motionEvent);

                Toast.makeText(WhatsappCameraActivity.this, "You reached to Maximum(25MB) video size.", Toast.LENGTH_SHORT).show();
            }


        }
    });

    mediaRecorder.setMaxFileSize(1000 * 25 * 1000);

    try {
        mediaRecorder.prepare();
    } catch (Exception e) {
        releaseMediaRecorder();
        e.printStackTrace();
        return false;
    }
    return true;

}
 
源代码15 项目: backgroundvideo   文件: VideoOverlay.java
public void Start(String filePath) throws Exception {
    if (this.mRecordingState == RecordingState.STARTED) {
        Log.w(TAG, "Already Recording");
        return;
    }

    if (!TextUtils.isEmpty(filePath)) {
        this.mFilePath = filePath;
    }

    attachView();

    if (this.mRecordingState == RecordingState.INITIALIZING) {
        this.mStartWhenInitialized = true;
        return;
    }

    if (TextUtils.isEmpty(mFilePath)) {
        throw new IllegalArgumentException("Filename for recording must be set");
    }

    initializeCamera();

    if (mCamera == null) {
        this.detachView();
        throw new NullPointerException("Cannot start recording, we don't have a camera!");
    }

    // Set camera parameters
    Camera.Parameters cameraParameters = mCamera.getParameters();
    mCamera.stopPreview(); //Apparently helps with freezing issue on some Samsung devices.
    mCamera.unlock();

    try {
        mRecorder = new MediaRecorder();
        mRecorder.setCamera(mCamera);

        CamcorderProfile profile;
        if (CamcorderProfile.hasProfile(mCameraId, CamcorderProfile.QUALITY_LOW)) {
            profile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_LOW);
        } else {
            profile = CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_HIGH);
        }

        Camera.Size lowestRes = CameraHelper.getLowestResolution(cameraParameters);
        profile.videoFrameWidth = lowestRes.width;
        profile.videoFrameHeight = lowestRes.height;

        mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        if (mRecordAudio) {
            // With audio
            mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mRecorder.setVideoFrameRate(profile.videoFrameRate);
            mRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
            mRecorder.setVideoEncodingBitRate(profile.videoBitRate);
            mRecorder.setAudioEncodingBitRate(profile.audioBitRate);
            mRecorder.setAudioChannels(profile.audioChannels);
            mRecorder.setAudioSamplingRate(profile.audioSampleRate);
            mRecorder.setVideoEncoder(profile.videoCodec);
            mRecorder.setAudioEncoder(profile.audioCodec);
        } else {
            // Without audio
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mRecorder.setVideoFrameRate(profile.videoFrameRate);
            mRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
            mRecorder.setVideoEncodingBitRate(profile.videoBitRate);
            mRecorder.setVideoEncoder(profile.videoCodec);
        }

        mRecorder.setOutputFile(filePath);
        mRecorder.setOrientationHint(mOrientation);
        mRecorder.prepare();
        Log.d(TAG, "Starting recording");
        mRecorder.start();
    } catch (Exception e) {
        this.releaseCamera();
        Log.e(TAG, "Could not start recording! MediaRecorder Error", e);
        throw e;
    }
}
 
public void startRecord(final String filePath, final String camera, final int width, final int height, final int quality, final boolean withFlash){
  Log.d(TAG, "CameraPreview startRecord camera: " + camera + " width: " + width + ", height: " + height + ", quality: " + quality);
  Activity activity = getActivity();
  muteStream(true, activity);
  if (this.mRecordingState == RecordingState.STARTED) {
    Log.d(TAG, "Already Recording");
    return;
  }

  this.recordFilePath = filePath;
  int mOrientationHint = calculateOrientationHint();
  int videoWidth = 0;//set whatever
  int videoHeight = 0;//set whatever

  Camera.Parameters cameraParams = mCamera.getParameters();
  if (withFlash) {
    cameraParams.setFlashMode(withFlash ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF);
    mCamera.setParameters(cameraParams);
    mCamera.startPreview();
  }

  mCamera.unlock();
  mRecorder = new MediaRecorder();

  try {
    mRecorder.setCamera(mCamera);

    CamcorderProfile profile;
    if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_HIGH)) {
      profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_HIGH);
    } else {
      if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_480P)) {
        profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_480P);
      } else {
        if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_720P)) {
          profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_720P);
        } else {
          if (CamcorderProfile.hasProfile(defaultCameraId, CamcorderProfile.QUALITY_1080P)) {
            profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_1080P);
          } else {
            profile = CamcorderProfile.get(defaultCameraId, CamcorderProfile.QUALITY_LOW);
          }
        }
      }
    }


    mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
    mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    mRecorder.setProfile(profile);
    mRecorder.setOutputFile(filePath);
    mRecorder.setOrientationHint(mOrientationHint);

    mRecorder.prepare();
    Log.d(TAG, "Starting recording");
    mRecorder.start();
    eventListener.onStartRecordVideo();
  } catch (IOException e) {
    eventListener.onStartRecordVideoError(e.getMessage());
  }
}
 
源代码17 项目: glass_snippets   文件: CameraService.java
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
	camera = Camera.open();
	try {
		mediaRecorder = new MediaRecorder();

		List<int[]> fps = camera.getParameters().getSupportedPreviewFpsRange();
		int preview_fps[] = fps.get(0);

		for (int i[] : camera.getParameters().getSupportedPreviewFpsRange())
			preview_fps = (mCaptureRate <= i[1] && mCaptureRate > i[0]) ? i : preview_fps;

		Camera.Parameters param = camera.getParameters();
		param.setVideoStabilization(true);
		param.setPreviewFpsRange(preview_fps[0], preview_fps[1]);
		camera.setParameters(param);
		camera.unlock();

		mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
		mediaRecorder.setCamera(camera);

		mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
		CamcorderProfile profile;
		if (mCaptureRate > 25) {
			mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
			profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
		} else {
			profile = CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_HIGH);
			mediaRecorder.setCaptureRate(mCaptureRate);
			profile.videoFrameRate = ((int) Math.ceil(mCaptureRate));
		}

		mediaRecorder.setProfile(profile);
		mediaRecorder.setOutputFile(mOutFile);

		mediaRecorder.prepare();
		mediaRecorder.start();

		ScaleAnimation a = new ScaleAnimation(3, 2, 3, 2);
		a.setDuration(2000);
		surfaceView.startAnimation(a);

		Log.i(TAG, String.format("recording %s with rate %.2f", mOutFile, mCaptureRate));
	} catch(Exception e) {
		onDestroy();
		Log.d(TAG, e.toString());
	}
}