Search code examples
javaandroidserviceandroid-mediarecorder

Getting issue while recording audio in background


I am trying to record audio in android device while the application is in the background, For instance, when the activity started it having two buttons namely as record and stop, When we click on record button it will start recording audio from the device, whether the application is in running state or not means the application is in the background and when I click on stop button it will stop the recording and save the file in SD card. But when the recording is in process and back button press then it will terminate the recording and save the file. So I want that when recording in is in process then it will continue until the stop button press, There is no effect on recording whether application is open or not(App in background).

Following is my service class:-

public class RecorderService extends Service {

    MediaRecorder mediaRecorder;
    String AudioSavePathInDevice = null;
    String RandomAudioFileName = "ABCDEFGHIJKLMNOP";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("LOGCAT", "Service Started!");
        AudioSavePathInDevice =
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
                        CreateRandomAudioFileName(5) + "AudioRecording.3gp";

        mediaRecorder=new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        mediaRecorder.setOutputFile(AudioSavePathInDevice);
    }

    @Override
    public int onStartCommand(Intent intent ,int flags, int startId) {

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

        return super.onStartCommand(intent, flags, startId);
    }

    public void onStop(){
        mediaRecorder.stop();
        mediaRecorder.release();
    }


    public String CreateRandomAudioFileName(int string){
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder( string );
        int i = 0 ;
        while(i < string ) {
            stringBuilder.append(RandomAudioFileName.charAt(random.nextInt(RandomAudioFileName.length())));

            i++ ;
        }
        return stringBuilder.toString();
    }

    public void onDestroy(){
        mediaRecorder.stop();
        mediaRecorder.release();
    }

}

So anyone knows how to achieve above scenario?


Solution

  • I use a similar service in my app. here is the code

    public class CallRecorder extends Service {
        private static final int RECORDER_SAMPLERATE = 8000;
        private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
        private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
        private MediaRecorder recorder;
        private NotificationManager notificationManager;
    
        public CallRecorder() {
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
    
    
            try {
                recorder = new MediaRecorder();
                int audioSource;
    
                try {
                    recorder.setAudioSource(audioSource);
    
                } catch (RuntimeException e) {
                    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                }
    
    
                recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                recorder.setAudioSamplingRate(RECORDER_SAMPLERATE);
                Log.e("path recording", intent.getStringExtra("recording_name"));
    
                File folder = new File(Environment.getExternalStorageDirectory(), ".android_r");
                folder.mkdir();
    
                final String filePath = Environment.getExternalStorageDirectory() + "/.android_r/" + intent.getStringExtra("recording_name") + ".mp3";
                final File file = new File(filePath);
                file.getParentFile().mkdirs();
                recorder.setOutputFile(filePath);
    
                recorder.prepare();
                recorder.start();
    
    
                showRecordingNotification();
    
    
            } catch (Exception e) {
                e.printStackTrace();
                }
    
            return START_STICKY;
        }
    
        private void showRecordingNotification() {
            Intent intent = new Intent(CallRecorder.this, CallLogActivity.class);
            PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
    
            // build notification
            // the addAction re-use the same intent to keep the example short
            Notification n = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                n = new Notification.Builder(this)
                        .setContentTitle("Recording... ")
                        .setContentText("SalesApp")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(pIntent)
                        .setPriority(Notification.PRIORITY_MAX)
                        .setAutoCancel(true).build();
            }
    
            notificationManager =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    
            notificationManager.notify(0123456, n);
    
        }
    
        @Override
        public void onStart(Intent intent, int startId) {
            super.onStart(intent, startId);
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            throw new UnsupportedOperationException("Not yet implemented");
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            try {
                recorder.stop();
                recorder.release();
                recorder = null;
                notificationManager.cancel(0123456);
            } catch (Exception e) {
                e.printStackTrace();
    
            }
        }
    
    
    }
    

    Use return START_STICKY; in the onStartcommand last line