Example usage for android.media MediaRecorder MediaRecorder

List of usage examples for android.media MediaRecorder MediaRecorder

Introduction

In this page you can find the example usage for android.media MediaRecorder MediaRecorder.

Prototype

public MediaRecorder() 

Source Link

Document

Default constructor.

Usage

From source file:com.example.recordvoice.service.RecordService.java

private boolean startMediaRecorder(int audioSource) {
    recorder = new MediaRecorder();
    try {//from   w  w w .  j a v a 2 s.  c  om
        recorder.reset();
        recorder.setAudioSource(audioSource);
        recorder.setAudioSamplingRate(8000);
        recorder.setAudioEncodingBitRate(12200);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        fileName = FileHelper.getFilename(phoneNumber, type, getApplicationContext());
        recorder.setOutputFile(fileName);

        OnErrorListener errorListener = new OnErrorListener() {
            public void onError(MediaRecorder arg0, int arg1, int arg2) {
                Log.e(Constants.TAG, "OnErrorListener " + arg1 + "," + arg2);
                terminateAndEraseFile();
            }
        };
        recorder.setOnErrorListener(errorListener);

        OnInfoListener infoListener = new OnInfoListener() {
            public void onInfo(MediaRecorder arg0, int arg1, int arg2) {
                Log.e(Constants.TAG, "OnInfoListener " + arg1 + "," + arg2);
                terminateAndEraseFile();
            }
        };
        recorder.setOnInfoListener(infoListener);

        recorder.prepare();
        // Sometimes prepare takes some time to complete
        Thread.sleep(2000);
        recorder.start();
        recording = true;
        return true;
    } catch (Exception e) {
        e.getMessage();
        return false;
    }
}

From source file:com.example.android.mediarecorder.MainActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private boolean prepareVideoRecorder() {
    if (!preparePreview()) {
        return false;
    }/*  www  . java  2s. c  o  m*/
    CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);

    // 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);

    // orientation
    int rotation = getWindowManager().getDefaultDisplay().getRotation();
    Log.i("TESTING", "Sensor Orientation: " + sensorOrientation);
    if (sensorOrientation == SENSOR_ORIENTATION_DEFAULT_DEGREES) {
        Log.i("TESTING", "Recorder: DEFAULT ROTATION: " + DEFAULT_ORIENTATIONS.get(rotation));
        mMediaRecorder.setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation));
    } else {
        Log.i("TESTING", "Recorder: INVERSING ROTATION: " + INVERSE_ORIENTATIONS.get(rotation));
        mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
    }

    // Step 4: Set output file
    mOutputFile = CameraHelper.getOutputMediaFile(CameraHelper.MEDIA_TYPE_VIDEO);
    if (mOutputFile == null) {
        return false;
    }
    mMediaRecorder.setOutputFile(mOutputFile.getPath());
    // END_INCLUDE (configure_media_recorder)

    // 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;
}

From source file:io.github.silencio_app.silencio.MainActivity.java

public void startMIC(View view) {

    /**//from  w  w w.  j  a v a  2  s .  co m
     * start the MIC if mediaRecorder instance is created else Pops up a message
     */
    if (mediaRecorder == null) {
        mediaRecorder = new MediaRecorder();
        mediaRecorder.reset();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setOutputFile("/dev/null"); // Not saving the audio

        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
            recording_flag = true;

            Thread newT = new Thread(new AudioListener()); // New Thread is created to handle the amplitude fetching and plotting graph
            newT.start();
            /*showGraph(view);*/

        } catch (IOException e) {
            Log.d(MSG, "================== EXCEPTION ================");
            e.printStackTrace();
        }

    }
}

From source file:wisc.drivesense.vediorecorder.CameraFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *///from  w  w w  .  j a v a2s .  c  o  m
private void openCamera(int width, int height) {

    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing()) {
        return;
    }

    int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        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.");
        }

        Log.d(TAG, "check how many cameras");
        for (int i = 0; i < manager.getCameraIdList().length; ++i) {
            Log.d(TAG, manager.getCameraIdList()[i]);
        }

        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();

        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);
        Log.e(TAG, "This camera does not suppport Camera2API");
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}

From source file:metrocasas.projectsgt.MainActivity.java

public void grabarAudio(View v) {
    myAudioRecorder = new MediaRecorder();
    myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    File path = new File(Environment.getExternalStorageDirectory().getPath());
    try {//  w  w  w  .  java2  s .co  m
        Long tsLong = System.currentTimeMillis() / 1000;
        audioFile = File.createTempFile("descripcion" + tsLong.toString(), ".3gp", path);
        audio = audioFile.getName();
    } catch (IOException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
    myAudioRecorder.setOutputFile(audioFile.getAbsolutePath());
    try {
        myAudioRecorder.prepare();
    } catch (IOException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
    myAudioRecorder.start();
    grabar.setEnabled(false);
    detener.setEnabled(true);
    escuchar.setEnabled(false);
}

From source file:org.botlibre.sdk.activity.MicConfiguration.java

public void recording(View v) {
    if (recording) {
        setMicIcon(true, true);/*from ww  w  .  jav  a  2s  .c  o  m*/
        try {
            //mediaPlayer
            myAudioRecorder = new MediaRecorder();
            myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
            myAudioRecorder.setOutputFile(outputFile);

            myAudioRecorder.prepare();
            myAudioRecorder.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        play.setEnabled(false);
        txt.setText("Status: Recording...");
        recording = false;
    } else {
        myAudioRecorder.stop();
        myAudioRecorder.release();
        play.setEnabled(true);
        txt.setText("Status: Audio Recorded");
        setMicIcon(false, false);
        recording = true;
    }
}

From source file:com.google.dotorg.crisisresponse.translationcards.RecordingActivity.java

private void startRecording() {
    if (!checkRecordingPermission()) {
        return;/*  www  . j  a  v a  2 s .  c o  m*/
    }
    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_%s_%d.3gp", dictionaryId, label.replace(' ', '-'), (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:edu.sfsu.csc780.chathub.ui.ChannelActivity.java

private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setOutputFile(mFileName);//from w  w  w . j a  va2 s  .  c o  m
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
    }

    mRecorder.start();
}

From source file:org.odk.collect.android.fragments.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `stateCallback`.
 *//* www.ja  va2 s.c  o  m*/
@SuppressWarnings("MissingPermission")
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 {
        Timber.d("tryAcquire");
        if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        String cameraId = null;
        for (String id : manager.getCameraIdList()) {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(id);
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing != CameraCharacteristics.LENS_FACING_FRONT) {
                continue;
            }
            // Choose the sizes for camera preview and video recording
            StreamConfigurationMap map = characteristics
                    .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            if (map == null) {
                continue;
            }
            videoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
            previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, videoSize);
            cameraId = id;
            break;
        }

        configureTransform(width, height);
        mediaRecorder = new MediaRecorder();
        manager.openCamera(cameraId, stateCallback, null);
    } catch (CameraAccessException e) {
        ToastUtils.showShortToast("Cannot access the camera.");
        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.android.camera2basic.Camera2VideoFragment.java

/**
 * Tries to open a {@link CameraDevice}. The result is listened by `mStateCallback`.
 *//*from  w w  w . ja  va 2 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 = 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);
        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.");
    }
}