For audio recording , Usually the normal Intent MediaStore.Audio.Media.RECORD_SOUND_ACTION
will work to record the audio and return the path back to the activity in onActivityResult()
method.
For that this the sample code.
int RQS_RECORDING = 1;
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, RQS_RECORDING);
In your OnActivityResult()
your code will be like this,
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RQS_RECORDING){
if(resultCode == Activity.RESULT_OK){
// Great! User has recorded and saved the audio file
if(data!=null)
{
String savedUri = data.getData();
Log.d("debug" , "Record Path:" + savedUri);
Toast.makeText(MainActivity.this,
"Saved: " + result,
Toast.LENGTH_LONG).show();
}
}
if (resultCode == Activity.RESULT_CANCELED) {
// Oops! User has canceled the recording
}
}
}
But Nope, It is not working for all the cases and some of the devices ( ex vivo V3 etc) recording is saved but it is not returning any data back i.e ( data is null) and some of the devices some additional options also in the recording ( like delete , retry , play , pause etc) which may also not required for us.
So Instead of the default Intent , you can create the custom Recording by using MediaRecorder
like below.
Sample Code.
AudioRecordActivity.Class
public class AudioRecordActivity extends AppCompatActivity {
Button buttonStart, buttonStop ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_record_activity);
buttonStart = (Button) findViewById(R.id.button);
buttonStop = (Button) findViewById(R.id.button2);
buttonStop.setEnabled(false);
random = new Random();
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(AudioRecordActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
Toast.makeText(AudioRecordActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",AudioSavePathInDevice);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(AudioRecordActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(AudioRecordActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AudioRecordActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
audio_record_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<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="40dp"
android:paddingLeft="40dp"
android:paddingRight="40dp"
android:paddingTop="40dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@mipmap/ic_launcher_round"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.STORAGE" />
So where ever you want to record the audio / sound you can simply use the below code and get your saved path back in result activity.
int RQS_RECORDING = 1;
Intent intent = new Intent(MainActivity.this , AudioRecordActivity.class);
startActivityForResult(intent, RQS_RECORDING);
OnActivityResult()
will be like this
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == RQS_RECORDING){
if(resultCode == Activity.RESULT_OK){
// Great! User has recorded and saved the audio file
String result=data.getStringExtra("result");
Toast.makeText(MainActivity.this,
"Saved: " + result,
Toast.LENGTH_LONG).show();
Log.d("debug" , "Saved Path::" + result);
}
if (resultCode == Activity.RESULT_CANCELED) {
// Oops! User has canceled the recording / back button
}
}
}
This is a sample code you can customize for your needs how you want for your requirement.
This is one library which providing the record controlling
For the second question, as i already given the link, you can use like below.
private void browseDocuments(){
String[] mimeTypes =
{"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf",
"application/zip"};
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
intent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent,"ChooseFile"), REQUEST_CODE_DOC);
}