Skip to main content

Android Audio Recording in Background with Service


 

In android audio recording is simple task but when it comes to record in background it becomes little bit difficult so here we are gonna explore audio recording with service.
How to record a audio when the app is running in background ?
In Android any task which has to be done in background we have to use extend Service Class.
How does this Service Class works?
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
AudioService.class
public class AudioService extends Service 
             implements MediaRecorder.OnInfoListener {

private MediaRecorder mRecorder;
//setting maximum file size to be recorded
private long Audio_MAX_FILE_SIZE = 1000000;//1Mb

private int[] amplitudes = new int[100];
private int i = 0;

private File mOutputFile;
@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, 
                               int startId) {
    super.onStartCommand(intent, flags, startId);
    return Service.START_STICKY;
}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    startRecording();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
private void startRecording() {
    mRecorder = new MediaRecorder();
    mRecorder.setOnInfoListener(this);
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setMaxFileSize(Audio_MAX_FILE_SIZE);
    mRecorder.setOutputFormat
                      (MediaRecorder.OutputFormat.MPEG_4);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
    {
     mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
     mRecorder.setAudioEncodingBitRate(48000);
    } else {
      mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
      mRecorder.setAudioEncodingBitRate(64000);
    }
    mRecorder.setAudioSamplingRate(16000);
    mOutputFile = getOutputFile();
    mOutputFile.getParentFile().mkdirs();
    mRecorder.setOutputFile(mOutputFile.getAbsolutePath());

    try {
        mRecorder.prepare();
        mRecorder.start();
        mStartTime = SystemClock.elapsedRealtime();
    } catch (IOException e) {
    }
}

protected void stopRecording(boolean saveFile) {
    mRecorder.stop();
    mRecorder.release();
    mRecorder = null;
    mStartTime = 0;
    if (!saveFile && mOutputFile != null) {
        mOutputFile.delete();
    }

    // to stop the service by itself
    stopSelf();

}
private File getOutputFile() {
    SimpleDateFormat dateFormat = new SimpleDateFormat
                 ("yyyyMMdd_HHmmssSSS", Locale.US);
    return new File(Environment.getExternalStorageDirectory()
             .getAbsolutePath().toString()
            + "/Voice Recorder/RECORDING_"
            + dateFormat.format(new Date())
            + ".m4a");
}
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
  //check whether file size has reached to 1MB to stop recording
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
    stopRecording(true);
}
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopRecording(true);
}

To stop or start the recording or service manually
In Fragment:
Start Service->
getActivity().startService(
new Intent(getActivity(), AudioService.class));

Stop Service->
getActivity().stopService(
new Intent(getActivity(), AudioService.class));
In Activity:
Start Service->
startService(new Intent(ClassName.this, AudioService.class));
Stop Service->
stopService(new Intent(getApplicationContext(),
 AudioService.class));
or
stopService(new Intent(ClassName.this,  
AudioService.class));






Comments

  1. Where you have defined mStartTime variable?

    ReplyDelete
    Replies
    1. @Ambuj you can define or declare mStartTime variable globally in your service class

      Delete
  2. How I use the fragment to start?

    ReplyDelete

Post a Comment

Popular posts from this blog

Vertical AutoScrolling TextView in Android

In android by default we can scroll the text in horizontal using marquee in layout, but if we want to scroll the text in vertical its not possible by default. So here we will learn to create a custom TextView which will auto-scroll in vertical direction. Source Code:  VerticalScrollingTextView-Android Create a AutoScrollingTextView.class which extends TextView: @SuppressLint ( "AppCompatCustomView" ) public class AutoScrollingTextView extends TextView { private static final float DEFAULT_SPEED = 65.0f ; public Scroller scroller ; public float speed = DEFAULT_SPEED ; public boolean continuousScrolling = true; public AutoScrollingTextView (Context context) { super (context) ; init( null, 0 ) ; scrollerInstance(context) ; } public AutoScrollingTextView (Context context , AttributeSet attrs) { super (context , attrs) ; init(attrs , 0 ) ; scr

Flexbox inside the RecyclerView as a LayoutManager (FlexboxLayoutManager).

Currently google has release the Flexbox which can be used for building flexible layouts using FlexboxLayout, it can be interpreted as an advanced LinearLayout because both layouts align their child views sequentially. For more detail on this flexbox-layout But here we are gonna work on Flexbox with RecyclerView. Flexbox with a large number of items in a scrollable container! Let's first see what are the Supported attributes / features comparison Due to some characteristics of the RecyclerView, some Flexbox attributes are not available/not implemented to the FlexboxLayoutManager. Here is a quick overview of the attributes/features comparison between the two containers. Attribute / Feature FlexboxLayout                FlexboxLayoutManager (RecyclerView) flexDirection flexWrap (except wrap_reverse ) justifyContent alignItems alignContent - layout_order - layout_flexGrow layout_flexShrink layout_alignSelf layout_fl

Android RecyclerView and StaggeredGridLayoutManager with Picasso/Glide

This project is there in GitHub https://github.com/yuvaraj119/Picasso-RecyclerView-StaggeredGridLayoutManager You can download and start customizing it for your project also. How to use with Picasso Picasso + RecyclerView + StaggeredGridLayoutManager Its the enhanced version of this project https://github.com/pohh/slotmachinepicasso were there was a problem with Picasso + RecyclerView + StaggeredGridLayoutManager shuffles resizable recycler views infinitely issue posted on github https://github.com/square/picasso/issues/918 I have made some changes now it works with Picasso and Glide without any shuffles and position change Currently this project is done with Picasso If you want to use it with Glide How to use with Glide Glide + RecyclerView + StaggeredGridLayoutManager Add dependencies for Glide https://github.com/bumptech/glide Remove Picasso library from dependency and remove all the codes of Picasso from MyGridAdapter.java and also from other p