Search code examples
androidaudioaudio-recording

record voice for a specific time period in android


I have two buttons, one for start recording and another for stop recording. i got success in recording sound and storing in sdcard:

now what i want is if i press stop button before 15 sec i should remain as it is, but if recording time going more then 15 sec it should automatically stop recording and store recorded file in sd card:

my code for recording sound is here :

**

public void startRecording(View view) throws IOException {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
        File sampleDir = Environment.getExternalStorageDirectory();
        try {
            //audiofile = File.createTempFile("sound", ".aac", sampleDir);
            audiofile = File.createTempFile("sound", ".m4a", sampleDir);
        } catch (IOException e) {
            Log.e(TAG, "sdcard access error");
            return;
        }
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        recorder.setOutputFile(audiofile.getAbsolutePath());
        recorder.prepare();
        recorder.start();


    }

**

and for stopping recording is

public void stopRecording(View view) {

        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        recorder.stop();
        recorder.release();

    } 

what should i do ?


Solution

  • Basically you will need to implement TimeTask for that.

     if (view.getId() == R.id.stop) {
                new Timer().schedule(new TimerTask() {
    
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {    
                            @Override
                            public void run() {
                                mediaRecorder.stop();
                                mediaRecorder.reset();
                                mediaRecorder.release();
                            }
                        });
    
                    }
    
                }, 15000); //<-- Execute code after 15000 ms i.e after 15 Seconds.
    
            }