I received the demand to do voice communication, I go, do you want to make a wechat, of course, we can not do that level, first try how to record. So try an example.

 

Take a look at the code for the recording:

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

The general process of the code is:

1. Set the sound source. The microphone is specified here

2. Specify the output format.

3. Specify the output file.

4. Specify the audio encoding format.

5. Prepare.

6. Start recording.

 

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.

 

———

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

}

This is, like, too easy. Specify a data source (the file to play).

So how do you terminate playback?

 mPlayer.release();

mPlayer = null;

All right. I admit it. It was all so simple. Android provides a very powerful package.

 ——

Post the classes I’ve wrapped for recording and playing.

 

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

 

 

Finally, the source code is available for download.