demand

Record using an Android phone

Understand the MediaRecorder

 mRecorder = new MediaRecorder();

mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(newFileName());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
    mRecorder.prepare();
} catch (IOException e) {
    Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
Copy the code

steps

  1. Set the sound source. The microphone is specified here
  2. Specify the output format.
  3. Specify the output file.
  4. Specifies the audio encoding format.
  5. Preparation.
  6. Start recording.

code

In conjunction with the start recording process, there will be a recording termination process, code:

mRecorder.stop();

mRecorder.release(); mRecorder = null; End and release resources.

play

When it’s done, you have to listen to it. Let’s watch the play:

mPlayer = new MediaPlayer();

try {
    mPlayer.setDataSource(fileName);
    mPlayer.prepare();
    mPlayer.start();
} catch (IOException e) {
    Log.e(LOG_TAG, "prepare() failed");
}
Copy the code

Stop playing

 mPlayer.release();
 mPlayer = null;
Copy the code

The complete code

class SoundRecorder { MediaRecorder mRecorder; boolean isRecording; public void startRecording() { mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mRecorder.setOutputFile(newFileName()); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { mRecorder.prepare(); } catch (IOException e) { Log.e(LOG_TAG, "prepare() failed"); } mRecorder.start(); } public void stopRecording() { mRecorder.stop(); mRecorder.release(); mRecorder = null; } public String newFileName() { String mFileName = Environment.getExternalStorageDirectory() .getAbsolutePath(); String s = new SimpleDateFormat("yyyy-MM-dd hhmmss") .format(new Date()); return mFileName += "/rcd_" + s + ".3gp"; } } public class SoundPlayer { MediaPlayer mPlayer; public void startPlaying(String fileName) { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(fileName); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { Log.e(LOG_TAG, "prepare() failed"); } } public void stopPlaying() { mPlayer.release(); mPlayer = null; }}Copy the code