Search in sources :

Example 6 with MediaRecorder

use of android.media.MediaRecorder in project android_frameworks_base by ParanoidAndroid.

the class MediaRecorderStressTest method recordVideoAndPlayback.

// Helper method for record & playback testing with different camcorder profiles
private void recordVideoAndPlayback(int profile) throws Exception {
    int iterations;
    int recordDuration;
    boolean removeVideo;
    int videoEncoder;
    int audioEncoder;
    int frameRate;
    int videoWidth;
    int videoHeight;
    int bitRate;
    if (profile != USE_TEST_RUNNER_PROFILE) {
        assertTrue(String.format("Camera doesn't support profile %d", profile), CamcorderProfile.hasProfile(CAMERA_ID, profile));
        CamcorderProfile camcorderProfile = CamcorderProfile.get(CAMERA_ID, profile);
        videoEncoder = camcorderProfile.videoCodec;
        audioEncoder = camcorderProfile.audioCodec;
        frameRate = camcorderProfile.videoFrameRate;
        videoWidth = camcorderProfile.videoFrameWidth;
        videoHeight = camcorderProfile.videoFrameHeight;
        bitRate = camcorderProfile.videoBitRate;
    } else {
        videoEncoder = MediaRecorderStressTestRunner.mVideoEncoder;
        audioEncoder = MediaRecorderStressTestRunner.mAudioEncoder;
        frameRate = MediaRecorderStressTestRunner.mFrameRate;
        videoWidth = MediaRecorderStressTestRunner.mVideoWidth;
        videoHeight = MediaRecorderStressTestRunner.mVideoHeight;
        bitRate = MediaRecorderStressTestRunner.mBitRate;
    }
    iterations = MediaRecorderStressTestRunner.mIterations;
    recordDuration = MediaRecorderStressTestRunner.mDuration;
    removeVideo = MediaRecorderStressTestRunner.mRemoveVideo;
    SurfaceHolder surfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder();
    mOutput.write("Total number of loops: " + iterations + "\n");
    try {
        mOutput.write("No of loop: ");
        for (int i = 0; i < iterations; i++) {
            String fileName = String.format("%s/temp%d%s", Environment.getExternalStorageDirectory(), i, OUTPUT_FILE_EXT);
            Log.v(TAG, fileName);
            runOnLooper(new Runnable() {

                @Override
                public void run() {
                    mRecorder = new MediaRecorder();
                }
            });
            Log.v(TAG, "iterations : " + iterations);
            Log.v(TAG, "video encoder : " + videoEncoder);
            Log.v(TAG, "audio encoder : " + audioEncoder);
            Log.v(TAG, "frame rate : " + frameRate);
            Log.v(TAG, "video width : " + videoWidth);
            Log.v(TAG, "video height : " + videoHeight);
            Log.v(TAG, "bit rate : " + bitRate);
            Log.v(TAG, "record duration : " + recordDuration);
            mRecorder.setOnErrorListener(mRecorderErrorCallback);
            mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setOutputFile(fileName);
            mRecorder.setVideoFrameRate(frameRate);
            mRecorder.setVideoSize(videoWidth, videoHeight);
            mRecorder.setVideoEncoder(videoEncoder);
            mRecorder.setAudioEncoder(audioEncoder);
            mRecorder.setVideoEncodingBitRate(bitRate);
            Log.v(TAG, "mediaRecorder setPreview");
            mRecorder.setPreviewDisplay(surfaceHolder.getSurface());
            mRecorder.prepare();
            mRecorder.start();
            Thread.sleep(recordDuration);
            Log.v(TAG, "Before stop");
            mRecorder.stop();
            mRecorder.release();
            //start the playback
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(fileName);
            mp.setDisplay(MediaFrameworkTest.mSurfaceView.getHolder());
            mp.prepare();
            mp.start();
            Thread.sleep(recordDuration);
            mp.release();
            validateRecordedVideo(fileName);
            if (removeVideo) {
                removeRecordedVideo(fileName);
            }
            if (i == 0) {
                mOutput.write(i + 1);
            } else {
                mOutput.write(String.format(", %d", (i + 1)));
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        fail("Record and playback");
    }
}
Also used : SurfaceHolder(android.view.SurfaceHolder) CamcorderProfile(android.media.CamcorderProfile) MediaRecorder(android.media.MediaRecorder) IOException(java.io.IOException) MediaPlayer(android.media.MediaPlayer)

Example 7 with MediaRecorder

use of android.media.MediaRecorder in project android_frameworks_base by ParanoidAndroid.

the class MediaRecorderStressTest method testStressTimeLapse.

// Test case for stressing time lapse
@LargeTest
public void testStressTimeLapse() throws Exception {
    SurfaceHolder mSurfaceHolder;
    mSurfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder();
    int recordDuration = MediaRecorderStressTestRunner.mTimeLapseDuration;
    boolean removeVideo = MediaRecorderStressTestRunner.mRemoveVideo;
    double captureRate = MediaRecorderStressTestRunner.mCaptureRate;
    Log.v(TAG, "Start camera time lapse stress:");
    mOutput.write("Total number of loops: " + NUMBER_OF_TIME_LAPSE_LOOPS + "\n");
    try {
        for (int i = 0, n = Camera.getNumberOfCameras(); i < n; i++) {
            mOutput.write("No of loop: camera " + i);
            for (int j = 0; j < NUMBER_OF_TIME_LAPSE_LOOPS; j++) {
                String fileName = String.format("%s/temp%d_%d%s", Environment.getExternalStorageDirectory(), i, j, OUTPUT_FILE_EXT);
                Log.v(TAG, fileName);
                runOnLooper(new Runnable() {

                    @Override
                    public void run() {
                        mRecorder = new MediaRecorder();
                    }
                });
                // Set callback
                mRecorder.setOnErrorListener(mRecorderErrorCallback);
                // Set video source
                mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
                // Set camcorder profile for time lapse
                CamcorderProfile profile = CamcorderProfile.get(j, CamcorderProfile.QUALITY_TIME_LAPSE_HIGH);
                mRecorder.setProfile(profile);
                // Set the timelapse setting; 0.1 = 10 sec timelapse, 0.5 = 2 sec timelapse, etc
                // http://developer.android.com/guide/topics/media/camera.html#time-lapse-video
                mRecorder.setCaptureRate(captureRate);
                // Set output file
                mRecorder.setOutputFile(fileName);
                // Set the preview display
                Log.v(TAG, "mediaRecorder setPreviewDisplay");
                mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
                mRecorder.prepare();
                mRecorder.start();
                Thread.sleep(recordDuration);
                Log.v(TAG, "Before stop");
                mRecorder.stop();
                mRecorder.release();
                // Start the playback
                MediaPlayer mp = new MediaPlayer();
                mp.setDataSource(fileName);
                mp.setDisplay(mSurfaceHolder);
                mp.prepare();
                mp.start();
                Thread.sleep(TIME_LAPSE_PLAYBACK_WAIT_TIME);
                mp.release();
                validateRecordedVideo(fileName);
                if (removeVideo) {
                    removeRecordedVideo(fileName);
                }
                if (j == 0) {
                    mOutput.write(j + 1);
                } else {
                    mOutput.write(String.format(", %d", (j + 1)));
                }
            }
        }
    } catch (IllegalStateException e) {
        Log.e(TAG, e.toString());
        fail("Camera time lapse stress test IllegalStateException");
    } catch (IOException e) {
        Log.e(TAG, e.toString());
        fail("Camera time lapse stress test IOException");
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        fail("Camera time lapse stress test Exception");
    }
}
Also used : CamcorderProfile(android.media.CamcorderProfile) IOException(java.io.IOException) IOException(java.io.IOException) SurfaceHolder(android.view.SurfaceHolder) MediaRecorder(android.media.MediaRecorder) MediaPlayer(android.media.MediaPlayer) LargeTest(android.test.suitebuilder.annotation.LargeTest)

Example 8 with MediaRecorder

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

the class CameraFragment method openCamera.

@Override
public void openCamera() {
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing())
        return;
    try {
        final int mBackCameraId = mInterface.getBackCamera() != null ? (Integer) mInterface.getBackCamera() : -1;
        final int mFrontCameraId = mInterface.getFrontCamera() != null ? (Integer) mInterface.getFrontCamera() : -1;
        if (mBackCameraId == -1 || mFrontCameraId == -1) {
            int numberOfCameras = Camera.getNumberOfCameras();
            if (numberOfCameras == 0) {
                throwError(new Exception("No cameras are available on this device."));
                return;
            }
            for (int i = 0; i < numberOfCameras; i++) {
                //noinspection ConstantConditions
                if (mFrontCameraId != -1 && mBackCameraId != -1)
                    break;
                Camera.CameraInfo info = new Camera.CameraInfo();
                Camera.getCameraInfo(i, info);
                if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT && mFrontCameraId == -1) {
                    mInterface.setFrontCamera(i);
                } else if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK && mBackCameraId == -1) {
                    mInterface.setBackCamera(i);
                }
            }
        }
        switch(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 && (Integer) mInterface.getFrontCamera() != -1) {
                        setImageRes(mButtonFacing, mInterface.iconRearCamera());
                        mInterface.setCameraPosition(CAMERA_POSITION_FRONT);
                    } else {
                        setImageRes(mButtonFacing, mInterface.iconFrontCamera());
                        if (mInterface.getBackCamera() != null && (Integer) mInterface.getBackCamera() != -1)
                            mInterface.setCameraPosition(CAMERA_POSITION_BACK);
                        else
                            mInterface.setCameraPosition(CAMERA_POSITION_UNKNOWN);
                    }
                } else {
                    // Check back facing first
                    if (mInterface.getBackCamera() != null && (Integer) mInterface.getBackCamera() != -1) {
                        setImageRes(mButtonFacing, mInterface.iconFrontCamera());
                        mInterface.setCameraPosition(CAMERA_POSITION_BACK);
                    } else {
                        setImageRes(mButtonFacing, mInterface.iconRearCamera());
                        if (mInterface.getFrontCamera() != null && (Integer) mInterface.getFrontCamera() != -1)
                            mInterface.setCameraPosition(CAMERA_POSITION_FRONT);
                        else
                            mInterface.setCameraPosition(CAMERA_POSITION_UNKNOWN);
                    }
                }
                break;
        }
        if (mWindowSize == null)
            mWindowSize = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(mWindowSize);
        final int toOpen = getCurrentCameraId();
        mCamera = Camera.open(toOpen == -1 ? 0 : toOpen);
        Camera.Parameters parameters = mCamera.getParameters();
        List<Camera.Size> videoSizes = parameters.getSupportedVideoSizes();
        if (videoSizes == null || videoSizes.size() == 0)
            videoSizes = parameters.getSupportedPreviewSizes();
        mVideoSize = chooseVideoSize((BaseCaptureActivity) activity, videoSizes);
        Camera.Size previewSize = chooseOptimalSize(parameters.getSupportedPreviewSizes(), mWindowSize.x, mWindowSize.y, mVideoSize);
        if (ManufacturerUtil.isSamsungGalaxyS3()) {
            parameters.setPreviewSize(ManufacturerUtil.SAMSUNG_S3_PREVIEW_WIDTH, ManufacturerUtil.SAMSUNG_S3_PREVIEW_HEIGHT);
        } else {
            parameters.setPreviewSize(previewSize.width, previewSize.height);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                parameters.setRecordingHint(true);
        }
        Camera.Size mStillShotSize = getHighestSupportedStillShotSize(parameters.getSupportedPictureSizes());
        parameters.setPictureSize(mStillShotSize.width, mStillShotSize.height);
        setCameraDisplayOrientation(parameters);
        mCamera.setParameters(parameters);
        // NOTE: onFlashModesLoaded should not be called while modifying camera parameters as
        //       the flash parameters set in setupFlashMode will then be overwritten
        mFlashModes = CameraUtil.getSupportedFlashModes(this.getActivity(), parameters);
        mInterface.setFlashModes(mFlashModes);
        onFlashModesLoaded();
        createPreview();
        mMediaRecorder = new MediaRecorder();
        onCameraOpened();
    } catch (IllegalStateException e) {
        throwError(new Exception("Cannot access the camera.", e));
    } catch (RuntimeException e2) {
        throwError(new Exception("Cannot access the camera, you may need to restart your device.", e2));
    }
}
Also used : Activity(android.app.Activity) Point(android.graphics.Point) Point(android.graphics.Point) Camera(android.hardware.Camera) MediaRecorder(android.media.MediaRecorder)

Example 9 with MediaRecorder

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

the class CameraFragment method prepareMediaRecorder.

private boolean prepareMediaRecorder() {
    try {
        final Activity activity = getActivity();
        if (null == activity)
            return false;
        final BaseCaptureInterface captureInterface = (BaseCaptureInterface) activity;
        setCameraDisplayOrientation(mCamera.getParameters());
        mMediaRecorder = new MediaRecorder();
        mCamera.stopPreview();
        mCamera.unlock();
        mMediaRecorder.setCamera(mCamera);
        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(getCurrentCameraId(), mInterface.qualityProfile());
        mMediaRecorder.setOutputFormat(profile.fileFormat);
        mMediaRecorder.setVideoFrameRate(mInterface.videoFrameRate(profile.videoFrameRate));
        mMediaRecorder.setVideoSize(mVideoSize.width, mVideoSize.height);
        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);
        mMediaRecorder.setPreviewDisplay(mPreviewView.getHolder().getSurface());
        try {
            mMediaRecorder.prepare();
            return true;
        } catch (Throwable e) {
            throwError(new Exception("Failed to prepare the media recorder: " + e.getMessage(), e));
            return false;
        }
    } catch (Throwable t) {
        try {
            mCamera.lock();
        } catch (IllegalStateException e) {
            throwError(new Exception("Failed to re-lock camera: " + e.getMessage(), e));
            return false;
        }
        t.printStackTrace();
        throwError(new Exception("Failed to begin recording: " + t.getMessage(), t));
        return false;
    }
}
Also used : Activity(android.app.Activity) CamcorderProfile(android.media.CamcorderProfile) MediaRecorder(android.media.MediaRecorder) Uri(android.net.Uri) Point(android.graphics.Point)

Example 10 with MediaRecorder

use of android.media.MediaRecorder in project Android-Developers-Samples by johnjohndoe.

the class MainActivity method prepareVideoRecorder.

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private boolean prepareVideoRecorder() {
    // BEGIN_INCLUDE (configure_preview)
    mCamera = CameraHelper.getDefaultCameraInstance();
    // We need to make sure that our preview and recording video size are supported by the
    // camera. Query camera to find all the sizes and choose the optimal size given the
    // dimensions of our preview surface.
    Camera.Parameters parameters = mCamera.getParameters();
    List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes();
    Camera.Size optimalSize = CameraHelper.getOptimalPreviewSize(mSupportedPreviewSizes, mPreview.getWidth(), mPreview.getHeight());
    // Use the same size for recording profile.
    CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
    profile.videoFrameWidth = optimalSize.width;
    profile.videoFrameHeight = optimalSize.height;
    // likewise for the camera object itself.
    parameters.setPreviewSize(profile.videoFrameWidth, profile.videoFrameHeight);
    mCamera.setParameters(parameters);
    try {
        // Requires API level 11+, For backward compatibility use {@link setPreviewDisplay}
        // with {@link SurfaceView}
        mCamera.setPreviewTexture(mPreview.getSurfaceTexture());
    } catch (IOException e) {
        Log.e(TAG, "Surface texture is unavailable or unsuitable" + e.getMessage());
        return false;
    }
    // END_INCLUDE (configure_preview)
    // BEGIN_INCLUDE (configure_media_recorder)
    mMediaRecorder = new MediaRecorder();
    // Step 1: Unlock and set camera to MediaRecorder
    mCamera.unlock();
    mMediaRecorder.setCamera(mCamera);
    // Step 2: Set sources
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
    mMediaRecorder.setProfile(profile);
    // Step 4: Set output file
    mMediaRecorder.setOutputFile(CameraHelper.getOutputMediaFile(CameraHelper.MEDIA_TYPE_VIDEO).toString());
    // Step 5: Prepare configured MediaRecorder
    try {
        mMediaRecorder.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;
}
Also used : CamcorderProfile(android.media.CamcorderProfile) Camera(android.hardware.Camera) IOException(java.io.IOException) MediaRecorder(android.media.MediaRecorder) TargetApi(android.annotation.TargetApi)

Aggregations

MediaRecorder (android.media.MediaRecorder)106 IOException (java.io.IOException)57 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 Camera (android.hardware.Camera)8 File (java.io.File)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