Recording Sound and Saving it in Android
Hey guys, in this blog we will see how to record sound in the android. The recorded sound will be saved in the "MediaRecorder" folder in your SD card. Run and test this project on the real device as it wont work on the emulator because emulators dont have mics to record.
activity_main.xml
MainActivity.java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/record" />
</RelativeLayout>
MainActivity.java
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
MediaRecorder mRecorder;
String filename="";
Button record;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
record = (Button) findViewById(R.id.record);
record.setOnClickListener(this);
}
private void record_and_save() {
// TODO Auto-generated method stub
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setAudioEncodingBitRate(64);
mRecorder.setAudioSamplingRate(48000);
filename = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(filename,"MediaRecorder");
if(!file.exists()) file.mkdirs();
filename = file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".wav";
mRecorder.setOutputFile(filename);
try {
mRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRecorder.start();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.record : record_and_save();break;
}
}
}
Comments
Post a Comment