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:de.azapps.mirakel.helper.TaskDialogHelpers.java

public static void handleAudioRecord(final Context context, final Task task,
        final ExecInterfaceWithTask onSuccess) {
    try {/*  ww w  .ja v a  2 s  .co m*/
        audio_record_mRecorder = new MediaRecorder();
        audio_record_mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        audio_record_mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        audio_record_filePath = FileUtils.getOutputMediaFile(FileUtils.MEDIA_TYPE_AUDIO).getAbsolutePath();
        audio_record_mRecorder.setOutputFile(audio_record_filePath);
        audio_record_mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        audio_record_mRecorder.prepare();
        audio_record_mRecorder.start();
    } catch (final Exception e) {
        Log.e(TAG, "prepare() failed");
        ErrorReporter.report(ErrorType.NO_SPEACH_RECOGNITION);
        return;
    }
    audio_record_alert_dialog = new AlertDialog.Builder(context).setTitle(R.string.audio_record_title)
            .setMessage(R.string.audio_record_message)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    Task mTask = task;
                    if (task == null || task.getId() == 0) {
                        ListMirakel listMirakel;
                        if (task == null) {
                            listMirakel = MirakelModelPreferences.getSafeImportDefaultList();
                        } else {
                            listMirakel = task.getList();
                        }
                        mTask = Semantic.createTask(MirakelCommonPreferences.getAudioDefaultTitle(),
                                Optional.fromNullable(listMirakel), true, context);
                    }
                    audio_record_mRecorder.stop();
                    audio_record_mRecorder.release();
                    audio_record_mRecorder = null;
                    mTask.addFile(context, Uri.fromFile(new File(audio_record_filePath)));
                    onSuccess.exec(mTask);
                }
            }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    cancelRecording();
                }
            }).setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(final DialogInterface dialog) {
                    cancelRecording();
                }
            }).show();
}

From source file:sg.fxl.topeka.widget.quiz.AudioQuizView.java

private boolean startRecording() {
    int permission = ActivityCompat.checkSelfPermission(getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int audioPermission = ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO);

    if (permission == PackageManager.PERMISSION_GRANTED
            && audioPermission == PackageManager.PERMISSION_GRANTED) {
        fileName = Environment.getExternalStorageDirectory().getAbsolutePath();
        fileName += "/" + System.currentTimeMillis() + ".mp4";

        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setOutputFile(fileName);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

        try {/*from  ww w.  jav  a  2s.  c  om*/
            recorder.prepare();
        } catch (IOException e) {
            Log.e(TAG, "prepare() failed");
        }

        recorder.start();
        return true;
    } else {
        // We don't have permission so prompt the user
        ActivityCompat
                .requestPermissions((Activity) getContext(),
                        new String[] { Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO },
                        1);
        return false;
    }
}

From source file:freed.cam.apis.camera2.modules.VideoModuleApi2.java

@TargetApi(VERSION_CODES.LOLLIPOP)
private void startPreviewVideo() {
    recordingFile = new File(cameraUiWrapper.getActivityInterface().getStorageHandler()
            .getNewFilePath(appSettingsManager.GetWriteExternal(), ".mp4"));
    mediaRecorder = new MediaRecorder();
    mediaRecorder.reset();//from  w  w  w . j a  v  a 2 s . c  o m
    mediaRecorder.setMaxFileSize(3037822976L); //~2.8 gigabyte
    mediaRecorder.setMaxDuration(7200000); //2hours
    mediaRecorder.setOnErrorListener(new OnErrorListener() {
        @Override
        public void onError(MediaRecorder mr, int what, int extra) {
            Log.d(TAG, "error MediaRecorder:" + what + "extra:" + extra);
            cameraUiWrapper.GetModuleHandler()
                    .onRecorderstateChanged(I_RecorderStateChanged.STATUS_RECORDING_STOP);
            changeCaptureState(ModuleHandlerAbstract.CaptureStates.video_recording_stop);
        }
    });

    mediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
        @Override
        public void onInfo(MediaRecorder mr, int what, int extra) {
            if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
                recordnextFile(mr);
            } else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
                recordnextFile(mr);
            }
        }
    });

    if (cameraUiWrapper.GetAppSettingsManager().getApiString(AppSettingsManager.SETTING_LOCATION)
            .equals(KEYS.ON)) {
        Location location = cameraUiWrapper.getActivityInterface().getLocationHandler().getCurrentLocation();
        if (location != null)
            mediaRecorder.setLocation((float) location.getLatitude(), (float) location.getLongitude());
    }
    switch (currentVideoProfile.Mode) {

    case Normal:
    case Highspeed:
        if (currentVideoProfile.isAudioActive)
            mediaRecorder.setAudioSource(AudioSource.CAMCORDER);
        break;
    case Timelapse:
        break;
    }
    mediaRecorder.setVideoSource(VideoSource.SURFACE);

    mediaRecorder.setOutputFormat(OutputFormat.MPEG_4);
    setRecorderFilePath();

    mediaRecorder.setVideoEncodingBitRate(currentVideoProfile.videoBitRate);

    try {
        cameraHolder.SetParameterRepeating(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
                new Range<>(currentVideoProfile.videoFrameRate, currentVideoProfile.videoFrameRate));
    } catch (Exception e) {
        e.printStackTrace();
    }

    //  if(currentVideoProfile.Mode == VideoMediaProfile.VideoMode.SlowMO)
    //     int SlowFactor = currentVideoProfile.videoFrameRate /30;

    if (currentVideoProfile.videoFrameRate == 120 && currentVideoProfile.videoFrameWidth == 1920)
        mediaRecorder.setVideoFrameRate(60);
    else
        mediaRecorder.setVideoFrameRate(currentVideoProfile.videoFrameRate);

    /*setCaptureRate
            
    Added in API level 11
    void setCaptureRate (double fps)
    Set video frame capture rate. This can be used to set a different video frame capture rate than the recorded video's playback rate.
    !!!!!! This method also sets the recording mode to time lapse.!!!!!
    In time lapse video recording, only video is recorded.
    Audio related parameters are ignored when a time lapse recording session starts, if an application sets them.*/
    //mediaRecorder.setCaptureRate((double)currentVideoProfile.videoFrameRate);
    mediaRecorder.setVideoSize(currentVideoProfile.videoFrameWidth, currentVideoProfile.videoFrameHeight);
    try {
        mediaRecorder.setVideoEncoder(currentVideoProfile.videoCodec);
    } catch (IllegalArgumentException ex) {
        mediaRecorder.reset();
        cameraUiWrapper.GetCameraHolder().SendUIMessage("VideoCodec not Supported");
    }

    switch (currentVideoProfile.Mode) {
    case Normal:
    case Highspeed:
        if (currentVideoProfile.isAudioActive) {
            try {
                mediaRecorder.setAudioEncoder(currentVideoProfile.audioCodec);
            } catch (IllegalArgumentException ex) {
                mediaRecorder.reset();
                cameraUiWrapper.GetCameraHolder().SendUIMessage("AudioCodec not Supported");
            }
            mediaRecorder.setAudioChannels(currentVideoProfile.audioChannels);
            mediaRecorder.setAudioEncodingBitRate(currentVideoProfile.audioBitRate);
            mediaRecorder.setAudioSamplingRate(currentVideoProfile.audioSampleRate);
        }
        break;
    case Timelapse:
        float frame = 30;
        if (!appSettingsManager.getApiString(AppSettingsManager.TIMELAPSEFRAME).equals(""))
            frame = Float.parseFloat(
                    appSettingsManager.getApiString(AppSettingsManager.TIMELAPSEFRAME).replace(",", "."));
        else
            appSettingsManager.setApiString(AppSettingsManager.TIMELAPSEFRAME, "" + frame);
        mediaRecorder.setCaptureRate(frame);
        break;
    }
    try {
        mediaRecorder.prepare();
    } catch (IOException ex) {
        ex.printStackTrace();
        cameraUiWrapper.GetModuleHandler().onRecorderstateChanged(I_RecorderStateChanged.STATUS_RECORDING_STOP);
        changeCaptureState(ModuleHandlerAbstract.CaptureStates.video_recording_stop);
        return;
    }
    recorderSurface = mediaRecorder.getSurface();
    cameraHolder.CaptureSessionH.AddSurface(recorderSurface, true);

    if (currentVideoProfile.Mode != VideoMediaProfile.VideoMode.Highspeed)
        cameraHolder.CaptureSessionH.CreateCaptureSession(previewrdy);
    else
        cameraHolder.CaptureSessionH.CreateHighSpeedCaptureSession(previewrdy);
}

From source file:net.micode.soundrecorder.RecorderService.java

private void localStartRecording(int outputfileformat, String path, boolean highQuality, long maxFileSize) {
    if (mRecorder == null) {
        mRemainingTimeCalculator.reset();
        if (maxFileSize != -1) {
            mRemainingTimeCalculator.setFileSizeLimit(new File(path), maxFileSize);
        }//from w w w.j a v  a 2  s.  c o  m

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);

        if (outputfileformat == MediaRecorder.OutputFormat.THREE_GPP) {
            mRemainingTimeCalculator.setBitRate(SoundRecorder.BITRATE_3GPP);
            //
            mRecorder.setAudioChannels(1);
            mRecorder.setAudioSamplingRate(mAudioSampleRate);
            mRecorder.setAudioEncodingBitRate(SoundRecorder.BITRATE_3GPP);
            mRecorder.setOutputFormat(outputfileformat);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        } else if (outputfileformat == MediaRecorder.OutputFormat.AMR_NB) {
            mRemainingTimeCalculator.setBitRate(SoundRecorder.BITRATE_AMR);
            mRecorder.setAudioSamplingRate(highQuality ? 16000 : 8000);

            mRecorder.setOutputFormat(outputfileformat);
            mRecorder.setAudioEncoder(
                    highQuality ? MediaRecorder.AudioEncoder.AMR_WB : MediaRecorder.AudioEncoder.AMR_NB);
        } else {
            mRemainingTimeCalculator.setBitRate(SoundRecorder.BITRATE_MP3);
            //
            mRecorder.setAudioChannels(1);
            mRecorder.setAudioSamplingRate(mAudioSampleRate);
            mRecorder.setAudioEncodingBitRate(SoundRecorder.BITRATE_MP3);
            mRecorder.setOutputFormat(outputfileformat);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        }

        mRecorder.setOutputFile(path);
        mRecorder.setOnErrorListener(this);

        // Handle IOException
        try {
            mRecorder.prepare();
        } catch (IOException exception) {
            sendErrorBroadcast(Recorder.INTERNAL_ERROR);
            mRecorder.reset();
            mRecorder.release();
            mRecorder = null;
            return;
        }
        // Handle RuntimeException if the recording couldn't start
        try {
            mRecorder.start();
        } catch (RuntimeException exception) {
            AudioManager audioMngr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            boolean isInCall = (audioMngr.getMode() == AudioManager.MODE_IN_CALL);
            if (isInCall) {
                sendErrorBroadcast(Recorder.IN_CALL_RECORD_ERROR);
            } else {
                sendErrorBroadcast(Recorder.INTERNAL_ERROR);
            }
            mRecorder.reset();
            mRecorder.release();
            mRecorder = null;
            return;
        }
        mFilePath = path;
        mStartTime = System.currentTimeMillis();
        mWakeLock.acquire();
        mNeedUpdateRemainingTime = false;
        sendStateBroadcast();
        showRecordingNotification();
        NotificationManager nMgr = (NotificationManager) getApplicationContext()
                .getSystemService(NOTIFICATION_SERVICE);
        nMgr.cancel(notifyID);
    }
}

From source file:com.prt.thirdeye.CamManager.java

public CamManager(Activity context) {
    mPreview = new CameraPreview();
    mMediaRecorder = new MediaRecorder();
    mCameraReady = true;//from w w w. j  av a2 s .c o m
    mHandler = new Handler();
    mIsModeSwitching = false;
    mContext = context;
    mPendingParameters = new ArrayList<NameValuePair>();
    mParametersThread = new ParametersThread();
    mParametersThread.start();
    mIsResuming = false;
    mIsRecordingHint = false;
    mRenderer = new CameraRenderer();
    mIsPreviewStarted = false;
}

From source file:com.callrecorder.android.RecordService.java

private void startRecording(Intent intent) {
    Log.d(Constants.TAG, "RecordService startRecording");
    boolean exception = false;
    recorder = new MediaRecorder();

    try {/*  www  .  ja  va2s . c om*/
        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        fileName = FileHelper.getFilename(phoneNumber);
        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;
        Log.d(Constants.TAG, "RecordService recorderStarted");
    } catch (IllegalStateException e) {
        Log.e(Constants.TAG, "IllegalStateException");
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        Log.e(Constants.TAG, "IOException");
        e.printStackTrace();
        exception = true;
    } catch (Exception e) {
        Log.e(Constants.TAG, "Exception");
        e.printStackTrace();
        exception = true;
    }

    if (exception) {
        terminateAndEraseFile();
    }

    if (recording) {
        Toast toast = Toast.makeText(this, this.getString(R.string.receiver_start_call), Toast.LENGTH_SHORT);
        toast.show();
    } else {
        Toast toast = Toast.makeText(this, this.getString(R.string.record_impossible), Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:metrocasas.projectsgt.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*w w  w. j  av a2s  . c  o  m*/

    userid = getIntent().getExtras().getString("id");

    //<editor-fold desc="Setting Map">
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();

    mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000) // 10 seconds, in milliseconds
            .setFastestInterval(1000); // 1 second, in milliseconds
    //</editor-fold>

    //<editor-fold desc="Setting Views">
    title = (EditText) findViewById(R.id.editTextTitle);
    front = (EditText) findViewById(R.id.editTextFrente);
    back = (EditText) findViewById(R.id.editTextBack);
    unities = (EditText) findViewById(R.id.editTextUnidades);
    developer = (EditText) findViewById(R.id.editTextDesarrollador);
    phone = (EditText) findViewById(R.id.editTextTelefono);

    p = (LinearLayout) findViewById(R.id.layoutprogress);
    q = (ScrollView) findViewById(R.id.layoutinfo);
    myAudioRecorder = new MediaRecorder();
    t1 = (TextView) findViewById(R.id.t1);
    upLoadInfo = (TextView) findViewById(R.id.tvUpload);
    grabar = (Button) findViewById(R.id.btnStart);
    detener = (Button) findViewById(R.id.btnStop);
    escuchar = (Button) findViewById(R.id.btnPlay);
    tomarFoto = (Button) findViewById(R.id.takePicture);
    obtenerGaleria = (Button) findViewById(R.id.getPicture);
    prevImg = (Button) findViewById(R.id.prevImg);
    nextImg = (Button) findViewById(R.id.nxtImg);
    licencia = (Spinner) findViewById(R.id.licencia);
    categoria = (Spinner) findViewById(R.id.categoria);
    enviar = (FloatingActionButton) findViewById(R.id.send_info);
    header = (ImageView) findViewById(R.id.imgHeader);
    Button btn_nuevo = (Button) findViewById(R.id.btnNew);
    openFile = (Button) findViewById(R.id.loadFile);
    audioNameFile = (TextView) findViewById(R.id.audioNameFile);
    //</editor-fold>

    assert btn_nuevo != null;
    btn_nuevo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ApartamentoDialog().show(getFragmentManager(), "");
        }
    });

    initializeImageSwitcher();
    setInitialImage();
    setImageRotateListener();

    header.setFocusableInTouchMode(true);
    header.requestFocus();
    header.requestFocusFromTouch();

    grabar.setEnabled(true);
    detener.setEnabled(false);
    escuchar.setEnabled(false);

    grabar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            grabarAudio(v);
        }
    });

    detener.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            detenerGrabacion(v);
        }
    });

    escuchar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            reproducir(v);
            escuchar.setEnabled(false);
        }
    });

    tomarFoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openBackCamera();
        }
    });

    obtenerGaleria.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openGallery();
        }
    });

    prevImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            prevImage();
        }
    });

    nextImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            nextImage();
        }
    });

    openFile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadFile();
        }
    });

    //<editor-fold desc="Setting Spinners">
    ArrayAdapter<CharSequence> staticAdapter2 = ArrayAdapter.createFromResource(this, R.array.list_license,
            android.R.layout.simple_spinner_item);
    staticAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    licencia.setAdapter(staticAdapter2);

    ArrayAdapter<CharSequence> staticAdapter3 = ArrayAdapter.createFromResource(this, R.array.list_category,
            android.R.layout.simple_spinner_item);
    staticAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    categoria.setAdapter(staticAdapter3);
    //</editor-fold>

    enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isNetworkAvailable()) {
                upLoadFiles();
            } else {
                Toast.makeText(getApplication(), "No tienes conexin a internet", Toast.LENGTH_LONG).show();
            }
        }
    });

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    aAdapter = new ApartamentoAdapter(listApartamento);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    assert recyclerView != null;
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(aAdapter);
    RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this,
            DividerItemDecoration.VERTICAL_LIST);
    recyclerView.addItemDecoration(itemDecoration);
    hello();

}

From source file:com.ktouch.kdc.launcher4.camera.CameraManager.java

public CameraManager(Activity context) {
    mPreview = new CameraPreview();
    mMediaRecorder = new MediaRecorder();
    mCameraReady = true;/*w  ww.  ja v  a 2s.  c o m*/
    mHandler = new Handler();
    mIsModeSwitching = false;
    mContext = context;
    mPendingParameters = new ArrayList<NameValuePair>();
    mParametersThread = new ParametersThread();
    mParametersThread.start();
    mIsResuming = false;
    mIsRecordingHint = false;
    mRenderer = new CameraRenderer();
    mIsPreviewStarted = false;
}

From source file:com.prashantmaurice.shadowfaxhackandroid.RecordService.java

private void startRecording(Intent intent) {
    Log.d(Constants.TAG, "RecordService startRecording");
    boolean exception = false;
    recorder = new MediaRecorder();

    try {//ww w.j  a  v a  2 s  .c o  m
        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        fileName = FileHelper.getFilename(phoneNumber);
        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;
        Log.d(Constants.TAG, "RecordService recorderStarted");
    } catch (IllegalStateException e) {
        Log.e(Constants.TAG, "IllegalStateException");
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        Log.e(Constants.TAG, "IOException");
        e.printStackTrace();
        exception = true;
    } catch (Exception e) {
        Log.e(Constants.TAG, "Exception");
        e.printStackTrace();
        exception = true;
    }

    if (exception) {
        terminateAndEraseFile();
    }

    if (recording) {
        Toast toast = Toast.makeText(this, this.getString(R.string.receiver_start_call), Toast.LENGTH_SHORT);
        toast.show();
    } else {
        Toast toast = Toast.makeText(this, this.getString(R.string.record_impossible), Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

public String getMicrophoneSample() {
    String out = "";
    String fileName = "microphone.3gp";

    MediaRecorder recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

    recorder.setOutputFile(MyApp.context.getFilesDir() + "/" + fileName);

    try {/* www  .  j a v  a 2  s.  c o  m*/
        recorder.prepare();
        recorder.start();
        Thread.sleep(5000);
        recorder.stop();
        recorder.release();

        File f = new File(MyApp.context.getFilesDir() + "/" + fileName);
        FileInputStream fileIn = MyApp.context.openFileInput(fileName);
        InputStreamReader isr = new InputStreamReader(fileIn);

        char[] tmpBuf = new char[(int) f.length()];
        isr.read(tmpBuf);
        out = new String(tmpBuf);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return out;
}