List of usage examples for android.media MediaRecorder MediaRecorder
public MediaRecorder()
From source file:com.czh.testmpeg.videorecord.CameraActivity.java
private boolean prepareMediaRecorder() { mediaRecorder = new MediaRecorder(); mCamera.unlock();//w w w . j a v a 2s . c om mediaRecorder.setCamera(mCamera); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { if (cameraFront) { mediaRecorder.setOrientationHint(270); } else { mediaRecorder.setOrientationHint(90); } } mediaRecorder.setProfile(CamcorderProfile.get(quality)); File file = new File("/mnt/sdcard/videokit"); if (!file.exists()) { file.mkdirs(); } Date d = new Date(); String timestamp = String.valueOf(d.getTime()); // url_file = Environment.getExternalStorageDirectory().getPath() + "/videoKit" + timestamp + ".mp4"; url_file = "/mnt/sdcard/videokit/in.mp4"; // url_file = "/mnt/sdcard/videokit/" + timestamp + ".mp4"; File file1 = new File(url_file); if (file1.exists()) { file1.delete(); } mediaRecorder.setOutputFile(url_file); // https://developer.android.com/reference/android/media/MediaRecorder.html#setMaxDuration(int) ?? // mediaRecorder.setMaxDuration(CameraConfig.MAX_DURATION_RECORD); // 60s. // https://developer.android.com/reference/android/media/MediaRecorder.html#setMaxFileSize(int) ?? // mediaRecorder.setMaxFileSize(CameraConfig.MAX_FILE_SIZE_RECORD); //size 1G try { mediaRecorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); releaseMediaRecorder(); return false; } catch (IOException e) { e.printStackTrace(); releaseMediaRecorder(); return false; } return true; }
From source file:mgumiero9.com.talentcubetest.view.Camera2VideoFragment.java
/** * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`. *///from ww w .j a v a2s . c o m private void openCamera(int width, int height) { if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) { requestVideoPermissions(); return; } final Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { Log.e(TAG, "tryAcquire"); if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } String cameraId = manager.getCameraIdList()[0]; // Choose the sizes for camera preview and video recording CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize); int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } else { mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth()); } configureTransform(width, height); mMediaRecorder = new MediaRecorder(); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } manager.openCamera(cameraId, mStateCallback, null); } catch (CameraAccessException e) { Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show(); activity.finish(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(), FRAGMENT_DIALOG); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening."); } }
From source file:com.example.zhang1ks.testbottombar.Camera2VideoFragment.java
/** * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`. *//* w ww.j a v a2 s . c o m*/ private void openCamera(int width, int height) { if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) { requestVideoPermissions(); return; } final Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { Log.d(TAG, "tryAcquire"); if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } String cameraId = mCameraId; // Choose the sizes for camera preview and video recording CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize); int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } else { mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth()); } configureTransform(width, height); mMediaRecorder = new MediaRecorder(); manager.openCamera(cameraId, mStateCallback, null); } catch (CameraAccessException e) { Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show(); activity.finish(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(), FRAGMENT_DIALOG); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening."); } }
From source file:org.mercycorps.translationcards.activity.RecordingActivity.java
private void startRecording() { if (!checkRecordingPermission()) { return;/*from www.j a va 2 s . com*/ } listenButton.setBackgroundResource(R.drawable.button_listen_enabled); if (!isAsset && (filename != null)) { File oldFile = new File(filename); oldFile.delete(); filename = null; } File recordingsDir = new File(getFilesDir(), "recordings"); recordingsDir.mkdirs(); File targetFile = new File(recordingsDir, String.format("%d.3gp", (new Random()).nextInt() * (new Random()).nextInt())); filename = targetFile.getAbsolutePath(); isAsset = false; mediaRecorder = new MediaRecorder(); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mediaRecorder.setOutputFile(filename); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { mediaRecorder.prepare(); } catch (IOException e) { Log.e(TAG, "Error preparing media recorder: " + e); // TODO(nworden): something } mediaRecorder.start(); recordButton.setBackgroundResource(R.drawable.button_record_active); recordingStatus = RecordingStatus.RECORDING; }
From source file:com.mov.android.camera2video.Camera2VideoFragment.java
/** * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`. */// w w w . j av a 2s . c o m private void openCamera(int width, int height, boolean isFront) { if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) { requestVideoPermissions(); return; } final Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { Log.d(TAG, "tryAcquire"); if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } String[] cameras = manager.getCameraIdList(); String cameraId = ""; for (String cameraId_ : cameras) { CameraCharacteristics cameraCharacteristics = manager.getCameraCharacteristics(cameraId_); if ((isFront && cameraCharacteristics .get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) || (!isFront && cameraCharacteristics.get( CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK)) { cameraId = cameraId_; break; } } // Choose the sizes for camera preview and video recording CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize); int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } else { mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth()); } configureTransform(width, height); mMediaRecorder = new MediaRecorder(); manager.openCamera(cameraId, mStateCallback, null); } catch (CameraAccessException e) { Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show(); activity.finish(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(R.string.camera_error)).show(getChildFragmentManager(), FRAGMENT_DIALOG); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening."); } }
From source file:kr.ac.kpu.wheeling.blackbox.Camera2VideoFragment.java
/** * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`. *///w ww . j a v a2 s .co m private void openCamera(int width, int height) { if (!hasPermissionsGranted(VIDEO_PERMISSIONS)) { requestVideoPermissions(); return; } final Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { Log.d(TAG, "tryAcquire"); if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } String cameraId = manager.getCameraIdList()[0]; // Choose the sizes for camera preview and video recording CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize); Log.d("INFO", "Width and Height: " + width + height); Log.d("INFO", "Video Height: " + mVideoSize.getHeight() + " Width: " + mVideoSize.getWidth()); Log.d("INFO", "Preview Height: " + mPreviewSize.getHeight() + " Width: " + mPreviewSize.getWidth()); screenInfo = new ScreenInfo(); screenInfo.setNoSoftKeyScreenInfo(activity); Log.d("SCREEN", screenInfo.toString()); int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight()); } else { mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth()); } configureTransform(width, height); mMediaRecorder = new MediaRecorder(); manager.openCamera(cameraId, mStateCallback, null); } catch (CameraAccessException e) { Toast.makeText(activity, "Cannot access the camera.", Toast.LENGTH_SHORT).show(); activity.finish(); } catch (NullPointerException e) { // Currently an NPE is thrown when the Camera2API is used but not supported on the // device this code runs. ErrorDialog.newInstance(getString(kr.ac.kpu.wheeling.R.string.camera_error)) .show(getChildFragmentManager(), FRAGMENT_DIALOG); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening."); } catch (SecurityException e) { } }
From source file:com.Yamate.Camera.Camera.java
/** * Opens the camera specified/*from w ww . j ava2s . c o m*/ */ private void openCamera(int width, int height) { setUpCameraOutputs(width, height); configureTransform(width, height); Activity activity = mActivity; //adding for camcorder mMediaRecorder = new MediaRecorder(); try { setUpMediaRecorder(); } catch (IOException e) { e.printStackTrace(); } CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening.", e); } catch (SecurityException e) { Log.e("mr", "cacPreviewSize - Security Exception"); } }
From source file:org.awesomeapp.messenger.ui.ConversationDetailActivity.java
public void startAudioRecording() { int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO); if (permissionCheck == PackageManager.PERMISSION_DENIED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. Snackbar.make(mConvoView.getHistoryView(), R.string.grant_perms, Snackbar.LENGTH_LONG).show(); } else {/*www.j av a2s. c o m*/ // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.RECORD_AUDIO }, MY_PERMISSIONS_REQUEST_AUDIO); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } } else { mMediaRecorder = new MediaRecorder(); String fileName = UUID.randomUUID().toString().substring(0, 8) + ".m4a"; mAudioFilePath = new File(getFilesDir(), fileName); mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //maybe we can modify these in the future, or allow people to tweak them mMediaRecorder.setAudioChannels(1); mMediaRecorder.setAudioEncodingBitRate(22050); mMediaRecorder.setAudioSamplingRate(64000); mMediaRecorder.setOutputFile(mAudioFilePath.getAbsolutePath()); try { mIsAudioRecording = true; mMediaRecorder.prepare(); mMediaRecorder.start(); } catch (Exception e) { Log.e(ImApp.LOG_TAG, "couldn't start audio", e); } } }
From source file:edu.sfsu.csc780.chathub.ui.MainActivity.java
private void startRecording() { recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(output_formats[currentFormat]); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); audioUri = getFilename();//w w w . j ava 2s.c om recorder.setOutputFile(audioUri); recorder.setOnErrorListener(errorListener); recorder.setOnInfoListener(infoListener); try { recorder.prepare(); recorder.start(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.insthub.O2OMobile.Activity.C1_PublishOrderActivity.java
/** * /*w w w . j av a 2s . co m*/ */ private void startRecording() { mFileName = newFileName(); // try { mRecorder = new MediaRecorder(); //? mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //??? mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); mRecorder.setAudioSamplingRate(8000); mRecorder.setAudioEncodingBitRate(16); //?? mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); mRecorder.setOutputFile(mFileName); mRecorder.prepare(); mRecorder.start(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e2) { e2.printStackTrace(); } mTimer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { // TODO Auto-generated method stub mMaxTime--; Message msg = new Message(); msg.what = mMaxTime; handler.sendMessage(msg); } }; mTimer.schedule(timerTask, 1000, 1000); }