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:org.apache.cordova.media.AudioPlayer.java

/**
 * Constructor./*from  w ww. ja v  a2 s  .c om*/
 *
 * @param handler           The audio handler object
 * @param id                The id of this audio player
 */
public AudioPlayer(AudioHandler handler, String id, String file) {
    this.handler = handler;
    this.id = id;
    this.audioFile = file;
    this.recorder = new MediaRecorder();

    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        this.tempFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording.3gp";
    } else {
        this.tempFile = "/data/data/" + handler.cordova.getActivity().getPackageName()
                + "/cache/tmprecording.3gp";
    }

}

From source file:fm.smart.r1.activity.CreateSoundActivity.java

public void onClick(View v) {
    String threegpfile_name = "test.3gp_amr";
    String amrfile_name = "test.amr";
    File dir = this.getDir("sounds", MODE_WORLD_READABLE);
    final File threegpfile = new File(dir, threegpfile_name);
    File amrfile = new File(dir, amrfile_name);
    String path = threegpfile.getAbsolutePath();
    Log.d("CreateSoundActivity", path);
    Log.d("CreateSoundActivity", (String) button.getText());
    if (button.getText().equals("Start")) {
        try {// w  w w . j  a va 2 s. co  m
            recorder = new MediaRecorder();

            // ContentValues values = new ContentValues(3);
            //
            // values.put(MediaStore.MediaColumns.TITLE, "test");
            // values.put(MediaStore.MediaColumns.DATE_ADDED,
            // System.currentTimeMillis());
            // values.put(MediaStore.MediaColumns.MIME_TYPE,
            // MediaRecorder.OutputFormat.THREE_GPP);
            //             
            // ContentResolver contentResolver = new ContentResolver(this);
            //             
            // Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
            // Uri newUri = contentResolver.insert(base, values);

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

            recorder.prepare();
            button.setText("Stop");
            recorder.start();
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    } else {
        FileOutputStream os = null;
        FileInputStream is = null;
        try {
            recorder.stop();
            recorder.release(); // Now the object cannot be reused
            button.setEnabled(false);

            // ThreegpReader tr = new ThreegpReader(threegpfile);
            // os = new FileOutputStream(amrfile);
            // tr.extractAmr(os);
            is = new FileInputStream(threegpfile);
            playSound(is.getFD());

            final String media_entity = "http://test.com/test.mp3";
            final String author = "tansaku";
            final String author_url = "http://smart.fm/users/tansaku";

            if (Main.isNotLoggedIn(this)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName(this, LoginActivity.class.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                LoginActivity.return_to = CreateSoundActivity.class.getName();
                LoginActivity.params = new HashMap<String, String>();
                LoginActivity.params.put("item_id", item_id);
                LoginActivity.params.put("list_id", list_id);
                LoginActivity.params.put("id", id);
                LoginActivity.params.put("to_record", to_record);
                LoginActivity.params.put("sound_type", sound_type);
                startActivity(intent);
            } else {

                final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
                myOtherProgressDialog.setTitle("Please Wait ...");
                myOtherProgressDialog.setMessage("Creating Sound ...");
                myOtherProgressDialog.setIndeterminate(true);
                myOtherProgressDialog.setCancelable(true);

                final Thread create_sound = new Thread() {
                    public void run() {
                        // TODO make this interruptable .../*if
                        // (!this.isInterrupted())*/
                        CreateSoundActivity.create_sound_result = createSound(threegpfile, media_entity, author,
                                author_url, "1", id);

                        myOtherProgressDialog.dismiss();

                    }
                };
                myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        create_sound.interrupt();
                    }
                });
                OnCancelListener ocl = new OnCancelListener() {
                    public void onCancel(DialogInterface arg0) {
                        create_sound.interrupt();
                    }
                };
                myOtherProgressDialog.setOnCancelListener(ocl);
                myOtherProgressDialog.show();
                create_sound.start();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

From source file:com.orpheusdroid.screenrecorder.RecorderService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //return super.onStartCommand(intent, flags, startId);
    //Find the action to perform from intent
    switch (intent.getAction()) {
    case Const.SCREEN_RECORDING_START:
        /* Wish MediaRecorder had a method isRecording() or similar. But, we are forced to
         * manage the state ourself. Let's hope the request is honored.
          * Request: https://code.google.com/p/android/issues/detail?id=800 */
        if (!isRecording) {
            //Get values from Default SharedPreferences
            getValues();//from  w w  w . ja  va 2 s . c  o  m
            Intent data = intent.getParcelableExtra(Const.RECORDER_INTENT_DATA);
            int result = intent.getIntExtra(Const.RECORDER_INTENT_RESULT, Activity.RESULT_OK);

            //Initialize MediaRecorder class and initialize it with preferred configuration
            mMediaRecorder = new MediaRecorder();
            initRecorder();

            //Set Callback for MediaProjection
            mMediaProjectionCallback = new MediaProjectionCallback();
            MediaProjectionManager mProjectionManager = (MediaProjectionManager) getSystemService(
                    Context.MEDIA_PROJECTION_SERVICE);

            //Initialize MediaProjection using data received from Intent
            mMediaProjection = mProjectionManager.getMediaProjection(result, data);
            mMediaProjection.registerCallback(mMediaProjectionCallback, null);

            /* Create a new virtual display with the actual default display
             * and pass it on to MediaRecorder to start recording */
            mVirtualDisplay = createVirtualDisplay();
            try {
                mMediaRecorder.start();
                isRecording = true;
                Toast.makeText(this, R.string.screen_recording_started_toast, Toast.LENGTH_SHORT).show();
            } catch (IllegalStateException e) {
                Log.d(Const.TAG,
                        "Mediarecorder reached Illegal state exception. Did you start the recording twice?");
                Toast.makeText(this, R.string.recording_failed_toast, Toast.LENGTH_SHORT).show();
                isRecording = false;
            }

            /* Add Pause action to Notification to pause screen recording if the user's android version
             * is >= Nougat(API 24) since pause() isnt available previous to API24 else build
             * Notification with only default stop() action */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //startTime is to calculate elapsed recording time to update notification during pause/resume
                startTime = System.currentTimeMillis();
                Intent recordPauseIntent = new Intent(this, RecorderService.class);
                recordPauseIntent.setAction(Const.SCREEN_RECORDING_PAUSE);
                PendingIntent precordPauseIntent = PendingIntent.getService(this, 0, recordPauseIntent, 0);
                NotificationCompat.Action action = new NotificationCompat.Action(
                        android.R.drawable.ic_media_pause,
                        getString(R.string.screen_recording_notification_action_pause), precordPauseIntent);

                //Start Notification as foreground
                startNotificationForeGround(createNotification(action).build(),
                        Const.SCREEN_RECORDER_NOTIFICATION_ID);
            } else
                startNotificationForeGround(createNotification(null).build(),
                        Const.SCREEN_RECORDER_NOTIFICATION_ID);
        } else {
            Toast.makeText(this, R.string.screenrecording_already_active_toast, Toast.LENGTH_SHORT).show();
        }
        break;
    case Const.SCREEN_RECORDING_PAUSE:
        pauseScreenRecording();
        break;
    case Const.SCREEN_RECORDING_RESUME:
        resumeScreenRecording();
        break;
    case Const.SCREEN_RECORDING_STOP:
        stopScreenSharing();
        //The service is started as foreground service and hence has to be stopped
        stopForeground(true);
        break;
    }
    return START_STICKY;
}

From source file:com.melonbear.ampup.MediaSectionFragment.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  va 2  s .  co m*/
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

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

    mRecorder.start();
}

From source file:com.commontime.cordova.audio.AudioPlayer.java

/**
 * Constructor./*from  w ww .  ja v  a  2 s  .co  m*/
 *
 * @param handler           The audio handler object
 * @param id                The id of this audio player
 */
public AudioPlayer(AudioHandler handler, String id, String file) {
    this.handler = handler;
    this.id = id;
    this.audioFile = file;
    this.recorder = new MediaRecorder();

    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        this.tempFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording.m4a";
    } else {
        this.tempFile = "/data/data/" + handler.cordova.getActivity().getPackageName()
                + "/cache/tmprecording.m4a";
    }

}

From source file:fm.smart.r1.CreateSoundActivity.java

public void onClick(View v) {
    String threegpfile_name = "test.3gp_amr";
    String amrfile_name = "test.amr";
    File dir = this.getDir("sounds", MODE_WORLD_READABLE);
    final File threegpfile = new File(dir, threegpfile_name);
    File amrfile = new File(dir, amrfile_name);
    String path = threegpfile.getAbsolutePath();
    Log.d("CreateSoundActivity", path);
    Log.d("CreateSoundActivity", (String) button.getText());
    if (button.getText().equals("Start")) {
        try {//from   w  w  w. ja va  2s  .c  o  m
            recorder = new MediaRecorder();

            // ContentValues values = new ContentValues(3);
            //
            // values.put(MediaStore.MediaColumns.TITLE, "test");
            // values.put(MediaStore.MediaColumns.DATE_ADDED,
            // System.currentTimeMillis());
            // values.put(MediaStore.MediaColumns.MIME_TYPE,
            // MediaRecorder.OutputFormat.THREE_GPP);
            //
            // ContentResolver contentResolver = new ContentResolver(this);
            //
            // Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI;
            // Uri newUri = contentResolver.insert(base, values);

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(path);

            recorder.prepare();
            button.setText("Stop");
            recorder.start();
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    } else {
        FileOutputStream os = null;
        FileInputStream is = null;
        try {
            recorder.stop();
            recorder.release(); // Now the object cannot be reused
            button.setEnabled(false);

            // ThreegpReader tr = new ThreegpReader(threegpfile);
            // os = new FileOutputStream(amrfile);
            // tr.extractAmr(os);
            is = new FileInputStream(threegpfile);
            playSound(is.getFD());

            final String media_entity = "http://test.com/test.mp3";
            final String author = "tansaku";
            final String author_url = "http://smart.fm/users/tansaku";

            if (LoginActivity.isNotLoggedIn(this)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName(this, LoginActivity.class.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                LoginActivity.return_to = CreateSoundActivity.class.getName();
                LoginActivity.params = new HashMap<String, String>();
                LoginActivity.params.put("item_id", item_id);
                LoginActivity.params.put("goal_id", goal_id);
                LoginActivity.params.put("id", id);
                LoginActivity.params.put("to_record", to_record);
                LoginActivity.params.put("sound_type", sound_type);
                startActivity(intent);
            } else {

                final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
                myOtherProgressDialog.setTitle("Please Wait ...");
                myOtherProgressDialog.setMessage("Creating Sound ...");
                myOtherProgressDialog.setIndeterminate(true);
                myOtherProgressDialog.setCancelable(true);

                final Thread create_sound = new Thread() {
                    public void run() {
                        // TODO make this interruptable .../*if
                        // (!this.isInterrupted())*/
                        CreateSoundActivity.create_sound_result = createSound(threegpfile, media_entity, author,
                                author_url, "1", item_id, id, to_record);
                        // this will also ensure item is in goal, but this
                        // should be sentence
                        // submission if we are handling sentence sound.
                        if (sound_type.equals(Integer.toString(R.id.cue_sound))) {
                            CreateSoundActivity.add_item_result = new AddItemResult(
                                    Main.lookup.addItemToGoal(Main.transport, Main.default_study_goal_id,
                                            item_id, CreateSoundActivity.create_sound_result.sound_id));
                        } else {
                            // ensure item is in goal
                            CreateSoundActivity.add_item_result = new AddItemResult(Main.lookup
                                    .addItemToGoal(Main.transport, Main.default_study_goal_id, item_id, null));
                            CreateSoundActivity.add_sentence_result = new AddSentenceResult(
                                    Main.lookup.addSentenceToGoal(Main.transport, Main.default_study_goal_id,
                                            item_id, id, CreateSoundActivity.create_sound_result.sound_id));

                        }
                        myOtherProgressDialog.dismiss();

                    }
                };
                myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        create_sound.interrupt();
                    }
                });
                OnCancelListener ocl = new OnCancelListener() {
                    public void onCancel(DialogInterface arg0) {
                        create_sound.interrupt();
                    }
                };
                myOtherProgressDialog.setOnCancelListener(ocl);
                myOtherProgressDialog.show();
                create_sound.start();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

From source file:com.hollandhaptics.babyapp.BabyService.java

/**
 * @brief Entry point of the Service./*from   www . j  av a2  s  .c  o m*/
 */
@SuppressLint("HardwareIds")
@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "BabyService Created");

    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    imei = telephonyManager.getDeviceId();
    Log.d(TAG, "IMEI: " + imei);

    upLoadServerUri = getResources().getString(R.string.file_upload_url);
    mhandler = new Handler();

    // Get the directory for the app's audio recordings.
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "BabyApp");
    if (!file.mkdirs()) {
        Log.e(TAG, "Directory not created");
    }
    path = file.toString();

    _recorder = new MediaRecorder();
}

From source file:mozilla.voicejam.singwithme.CameraActivity.java

void record() {
    try {//from  www.  java2s.  c  o m
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

        File file = File.createTempFile("raw", ".amr", this.getExternalFilesDir(null));
        filePath = file.getAbsolutePath();

        mediaRecorder.setOutputFile(filePath);
        mediaRecorder.prepare();
        mediaRecorder.start();
        Toast.makeText(this, filePath, Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(this, "FileIOException", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }

}

From source file:com.intel.xdk.audio.Audio.java

public void startRecording(String format, int samplingRate, int numChannels) {
    int encodeFormat = MediaRecorder.AudioEncoder.DEFAULT;

    if (format.toUpperCase().matches("AMR_NB"))
        encodeFormat = MediaRecorder.AudioEncoder.AMR_NB;
    if (mediaRecorder != null) {
        injectJS(//from  www.jav a 2 s.  com
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.audio.record.busy',true,true);document.dispatchEvent(ev);");
        return;
    }
    mediaRecorder = new MediaRecorder();
    String filePath = null, baseName = null;
    File outFile;
    int i = 0;
    do {
        baseName = String.format("recording_%1$03d.amr", i++);
        filePath = String.format("%1$s/%2$s", recordingDirectory.getAbsolutePath(), baseName);
        outFile = new File(filePath);
    } while (outFile.exists());
    recordingFileName = baseName;
    mediaRecorder.setOnErrorListener(recordOnError);
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setAudioEncoder(encodeFormat);
    mediaRecorder.setAudioChannels(numChannels);
    if (samplingRate > 0)
        mediaRecorder.setAudioSamplingRate(samplingRate);
    mediaRecorder.setOutputFile(filePath);
    try {
        mediaRecorder.prepare();
        mediaRecorder.start(); // Recording is now started
    } catch (Exception e) {
        injectJS("javascript:var ev = document.createEvent('Events');"
                + "ev.initEvent('intel.xdk.audio.record.error',true,true);document.dispatchEvent(ev);");
        mediaRecorder.release();
        mediaRecorder = null;
        return;
    }
    injectJS("javascript:var ev = document.createEvent('Events');"
            + "ev.initEvent('intel.xdk.audio.record.start',true,true);document.dispatchEvent(ev);");
}

From source file:com.ppdl.microphone.MainActivity.java

public void startRecording() {
    mMediaRecorder = new MediaRecorder();
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
    mMediaRecorder.setOutputFile(newRecordName());
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    try {/*from   www  .ja v  a 2  s  .co m*/
        mMediaRecorder.prepare();
        mMediaRecorder.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}