Search in sources :

Example 66 with MediaRecorder

use of android.media.MediaRecorder in project cw-omnibus by commonsguy.

the class MainActivity method onStart.

@Override
public void onStart() {
    super.onStart();
    recorder = new MediaRecorder();
    recorder.setOnErrorListener(this);
    recorder.setOnInfoListener(this);
}
Also used : MediaRecorder(android.media.MediaRecorder)

Example 67 with MediaRecorder

use of android.media.MediaRecorder in project cw-omnibus by commonsguy.

the class MainActivity method onStart.

@Override
public void onStart() {
    super.onStart();
    recorder = new MediaRecorder();
    recorder.setOnErrorListener(this);
    recorder.setOnInfoListener(this);
}
Also used : MediaRecorder(android.media.MediaRecorder)

Example 68 with MediaRecorder

use of android.media.MediaRecorder in project material-camera by afollestad.

the class Camera2Fragment method openCamera.

@Override
public void openCamera() {
    final int width = mTextureView.getWidth();
    final int height = mTextureView.getHeight();
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing())
        return;
    final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throwError(new Exception("Time out waiting to lock camera opening."));
            return;
        }
        if (mInterface.getFrontCamera() == null || mInterface.getBackCamera() == null) {
            for (String cameraId : manager.getCameraIdList()) {
                if (cameraId == null)
                    continue;
                if (mInterface.getFrontCamera() != null && mInterface.getBackCamera() != null)
                    break;
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
                //noinspection ConstantConditions
                int facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing == CameraCharacteristics.LENS_FACING_FRONT)
                    mInterface.setFrontCamera(cameraId);
                else if (facing == CameraCharacteristics.LENS_FACING_BACK)
                    mInterface.setBackCamera(cameraId);
            }
        }
        switch(mInterface.getCurrentCameraPosition()) {
            case CAMERA_POSITION_FRONT:
                setImageRes(mButtonFacing, mInterface.iconRearCamera());
                break;
            case CAMERA_POSITION_BACK:
                setImageRes(mButtonFacing, mInterface.iconFrontCamera());
                break;
            case CAMERA_POSITION_UNKNOWN:
            default:
                if (getArguments().getBoolean(CameraIntentKey.DEFAULT_TO_FRONT_FACING, false)) {
                    // Check front facing first
                    if (mInterface.getFrontCamera() != null) {
                        setImageRes(mButtonFacing, mInterface.iconRearCamera());
                        mInterface.setCameraPosition(CAMERA_POSITION_FRONT);
                    } else {
                        setImageRes(mButtonFacing, mInterface.iconFrontCamera());
                        if (mInterface.getBackCamera() != null)
                            mInterface.setCameraPosition(CAMERA_POSITION_BACK);
                        else
                            mInterface.setCameraPosition(CAMERA_POSITION_UNKNOWN);
                    }
                } else {
                    // Check back facing first
                    if (mInterface.getBackCamera() != null) {
                        setImageRes(mButtonFacing, mInterface.iconFrontCamera());
                        mInterface.setCameraPosition(CAMERA_POSITION_BACK);
                    } else {
                        setImageRes(mButtonFacing, mInterface.iconRearCamera());
                        if (mInterface.getFrontCamera() != null)
                            mInterface.setCameraPosition(CAMERA_POSITION_FRONT);
                        else
                            mInterface.setCameraPosition(CAMERA_POSITION_UNKNOWN);
                    }
                }
                break;
        }
        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics((String) mInterface.getCurrentCameraId());
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        assert map != null;
        // For still image captures, we use the largest available size.
        Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea());
        // Find out if we need to swap dimension to get the preview size relative to sensor
        // coordinate.
        int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        //noinspection ConstantConditions,ResourceType
        @Degrees.DegreeUnits final int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        @Degrees.DegreeUnits int deviceRotation = Degrees.getDisplayRotation(getActivity());
        mDisplayOrientation = Degrees.getDisplayOrientation(sensorOrientation, deviceRotation, getCurrentCameraPosition() == CAMERA_POSITION_FRONT);
        Log.d("Camera2Fragment", String.format("Orientations: Sensor = %d˚, Device = %d˚, Display = %d˚", sensorOrientation, deviceRotation, mDisplayOrientation));
        if (mInterface.useStillshot()) {
            boolean swappedDimensions = false;
            switch(displayRotation) {
                case Surface.ROTATION_0:
                case Surface.ROTATION_180:
                    if (sensorOrientation == Degrees.DEGREES_90 || sensorOrientation == Degrees.DEGREES_270) {
                        swappedDimensions = true;
                    }
                    break;
                case Surface.ROTATION_90:
                case Surface.ROTATION_270:
                    if (sensorOrientation == Degrees.DEGREES_0 || sensorOrientation == Degrees.DEGREES_180) {
                        swappedDimensions = true;
                    }
                    break;
                default:
                    Log.e("stillshot", "Display rotation is invalid: " + displayRotation);
            }
            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            int rotatedPreviewWidth = width;
            int rotatedPreviewHeight = height;
            int maxPreviewWidth = displaySize.x;
            int maxPreviewHeight = displaySize.y;
            if (swappedDimensions) {
                rotatedPreviewWidth = height;
                rotatedPreviewHeight = width;
                maxPreviewWidth = displaySize.y;
                maxPreviewHeight = displaySize.x;
            }
            if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                maxPreviewWidth = MAX_PREVIEW_WIDTH;
            }
            if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                maxPreviewHeight = MAX_PREVIEW_HEIGHT;
            }
            // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
            // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
            // garbage capture data.
            mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest);
            mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, 2);
            mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {

                @Override
                public void onImageAvailable(ImageReader reader) {
                    Image image = reader.acquireNextImage();
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    final byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    final File outputPic = getOutputPictureFile();
                    FileOutputStream output = null;
                    try {
                        output = new FileOutputStream(outputPic);
                        output.write(bytes);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        image.close();
                        if (null != output) {
                            try {
                                output.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    Log.d("stillshot", "picture saved to disk - jpeg, size: " + bytes.length);
                    mOutputUri = Uri.fromFile(outputPic).toString();
                    mInterface.onShowStillshot(mOutputUri);
                }
            }, mBackgroundHandler);
        } else {
            mMediaRecorder = new MediaRecorder();
            mVideoSize = chooseVideoSize((BaseCaptureInterface) activity, map.getOutputSizes(MediaRecorder.class));
            mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);
        }
        int orientation = VideoStreamView.getScreenOrientation(activity);
        if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        mAfAvailable = false;
        int[] afModes = characteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES);
        if (afModes != null) {
            for (int i : afModes) {
                if (i != 0) {
                    mAfAvailable = true;
                    break;
                }
            }
        }
        configureTransform(width, height);
        mInterface.setFlashModes(CameraUtil.getSupportedFlashModes(getActivity(), characteristics));
        onFlashModesLoaded();
        // noinspection ResourceType
        manager.openCamera((String) mInterface.getCurrentCameraId(), mStateCallback, null);
    } catch (CameraAccessException e) {
        throwError(new Exception("Cannot access the camera.", e));
    } catch (NullPointerException e) {
        // Currently an NPE is thrown when the Camera2API is used but not supported on the
        // device this code runs.
        new ErrorDialog().show(getFragmentManager(), "dialog");
    } catch (InterruptedException e) {
        throwError(new Exception("Interrupted while trying to lock camera opening.", e));
    }
}
Also used : Size(android.util.Size) Activity(android.app.Activity) Image(android.media.Image) CameraAccessException(android.hardware.camera2.CameraAccessException) ImageReader(android.media.ImageReader) CameraManager(android.hardware.camera2.CameraManager) StreamConfigurationMap(android.hardware.camera2.params.StreamConfigurationMap) Point(android.graphics.Point) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Point(android.graphics.Point) IOException(java.io.IOException) CameraAccessException(android.hardware.camera2.CameraAccessException) FileOutputStream(java.io.FileOutputStream) CameraCharacteristics(android.hardware.camera2.CameraCharacteristics) MediaRecorder(android.media.MediaRecorder) File(java.io.File)

Example 69 with MediaRecorder

use of android.media.MediaRecorder in project material-camera by afollestad.

the class Camera2Fragment method setUpMediaRecorder.

private boolean setUpMediaRecorder() {
    final Activity activity = getActivity();
    if (null == activity)
        return false;
    final BaseCaptureInterface captureInterface = (BaseCaptureInterface) activity;
    if (mMediaRecorder == null)
        mMediaRecorder = new MediaRecorder();
    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.SURFACE);
    final CamcorderProfile profile = CamcorderProfile.get(0, mInterface.qualityProfile());
    mMediaRecorder.setOutputFormat(profile.fileFormat);
    mMediaRecorder.setVideoFrameRate(mInterface.videoFrameRate(profile.videoFrameRate));
    mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
    mMediaRecorder.setVideoEncodingBitRate(mInterface.videoEncodingBitRate(profile.videoBitRate));
    mMediaRecorder.setVideoEncoder(profile.videoCodec);
    if (canUseAudio && audioEnabled) {
        mMediaRecorder.setAudioEncodingBitRate(mInterface.audioEncodingBitRate(profile.audioBitRate));
        mMediaRecorder.setAudioChannels(profile.audioChannels);
        mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate);
        mMediaRecorder.setAudioEncoder(profile.audioCodec);
    }
    Uri uri = Uri.fromFile(getOutputMediaFile());
    mOutputUri = uri.toString();
    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(mDisplayOrientation);
    try {
        mMediaRecorder.prepare();
        return true;
    } catch (Throwable e) {
        throwError(new Exception("Failed to prepare the media recorder: " + e.getMessage(), e));
        return false;
    }
}
Also used : Activity(android.app.Activity) CamcorderProfile(android.media.CamcorderProfile) MediaRecorder(android.media.MediaRecorder) Uri(android.net.Uri) Point(android.graphics.Point) IOException(java.io.IOException) CameraAccessException(android.hardware.camera2.CameraAccessException)

Example 70 with MediaRecorder

use of android.media.MediaRecorder in project robolectric by robolectric.

the class ShadowMediaRecorderTest method setUp.

@Before
public void setUp() throws Exception {
    mediaRecorder = new MediaRecorder();
    shadowMediaRecorder = Shadows.shadowOf(mediaRecorder);
}
Also used : MediaRecorder(android.media.MediaRecorder) Before(org.junit.Before)

Aggregations

MediaRecorder (android.media.MediaRecorder)107 IOException (java.io.IOException)58 MediaPlayer (android.media.MediaPlayer)18 Paint (android.graphics.Paint)15 CamcorderProfile (android.media.CamcorderProfile)15 SurfaceHolder (android.view.SurfaceHolder)12 Surface (android.view.Surface)11 File (java.io.File)9 Camera (android.hardware.Camera)8 MutableFrameFormat (android.filterfw.core.MutableFrameFormat)6 Point (android.filterfw.geometry.Point)6 StreamConfigurationMap (android.hardware.camera2.params.StreamConfigurationMap)6 LargeTest (android.test.suitebuilder.annotation.LargeTest)6 Size (android.util.Size)6 Canvas (android.graphics.Canvas)5 Range (android.util.Range)5 SimpleCaptureCallback (com.android.mediaframeworktest.helpers.CameraTestUtils.SimpleCaptureCallback)5 Activity (android.app.Activity)4 Point (android.graphics.Point)4 Uri (android.net.Uri)3