Friday, June 5, 2015

// //

Save an audio file into a specific folder in android

hi Guys, now i want to show you how to record audio and set the audio file into specific folder. pls, don't hesitate to comment if you are having problems. The activitymain.xml



    
import java.io.File;
import java.io.IOException;

import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {
 
  Button startButton;
     Button stopButton;
     MediaRecorder recorder;
     String path="/sdcard/media/alarms/";
     String audioname = "sample.mp4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        startButton = (Button) findViewById(R.id.button1);
        stopButton = (Button) findViewById(R.id.button2);

        stopButton.setEnabled(false);
       //make directory
        boolean exists = (new File(path)).exists();
   if (!exists){new File(path).mkdirs();}
     
    }

    public void onStartClicked(View v) throws Exception{

        startButton.setEnabled(false);
        stopButton.setEnabled(true);

        recorder = new MediaRecorder();
 
   
   recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
   recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
   recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC );
  // recorder.setMaxDuration(50000); // 50 seconds
   recorder.setAudioEncodingBitRate(160 * 1024);    
   //recorder.setAudioChannels(2);
   recorder.setOutputFile(path+audioname );
  
//try and catch 
  try {
   recorder.prepare();
  } catch (IllegalStateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
  
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
      
  
  recorder.start();     
   }
 

    public void onStopClicked(View v) {
        startButton.setEnabled(true);
        stopButton.setEnabled(false);

        recorder.stop();
        recorder.reset();
        recorder.release();
        recorder = null;
     
     
        Toast.makeText(getApplicationContext(), "Audio recorded successfully", Toast.LENGTH_LONG).show();
    }
}

And add this permission to your Android Manifest:

    
     
Now go to your sd card and find the path!... now don't hesitate to comment if your having problems!


You may also like:Delete the latest file from any specific folder in sdcard in android