Search code examples
androidaudio-recordingandroid-audiorecord

Problem with AudioRecord class


I am recording audio using AudioRecord class.I want to record audio into a particular file in my asset folder or resource folder.I think there is no problem in recording.but while reading buffer it is showing some problem(it is throwing NullPointerException).Can anyone suggest what may be the problem?


Solution

  • You can not save file inside Asset folder. Assets folder is read only instead of it you will have to save it in the internal or external storage of your device

    Below there is a core to record the media file.

    package com.example.media.record;
    
        import java.io.File;
        import java.io.IOException;
    
        import android.app.Activity;
        import android.media.MediaPlayer;
        import android.media.MediaPlayer.OnCompletionListener;
        import android.media.MediaPlayer.OnErrorListener;
        import android.media.MediaRecorder;
        import android.os.Bundle;
        import android.os.Environment;
        import android.os.Handler;
        import android.os.Handler.Callback;
        import android.os.Message;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.ProgressBar;
        import android.widget.Toast;
    
        public class MediaRecorderActivity extends Activity implements OnClickListener {
            Button btnPlay;
            Button btnRecord;
            ProgressBar progress;
            MediaPlayer mPlayer;
            MediaRecorder mRecorder;
            String mFileName;
            boolean mStartRecording = true;
            boolean mStartPlaying = true;
            Thread mThreadProgress;
            int duration = 1;
            private void onRecord(boolean start) {
                if(start) {
                    startRecording();
                }else {
                    stopRecording();
                }
            }
    
            private void onPlay(boolean start) {
                if(start) {
                    startPlaying();
                }else {
                    stopPlaying();
                }
            }
    
            private void startRecording() {
                mRecorder = new MediaRecorder();
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mRecorder.setOutputFile(mFileName);
                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                mRecorder.setOnErrorListener(errorListenerForRecorder);
    
                try {
                    mRecorder.prepare();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    mRecorder.start();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Error :: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
    
            }
    
    
            private void stopRecording() {
                if(mRecorder != null) {
                    mRecorder.stop();
                    mRecorder.release();
                    mRecorder = null;
                }
            }
    
            private void startPlaying() {
                mPlayer = new MediaPlayer();
                try {
                    mPlayer.setDataSource(mFileName);
                    mPlayer.setOnCompletionListener(completionListener);
                    mPlayer.setOnErrorListener(errorListenerForPlayer);
                    mPlayer.prepare();
                    mPlayer.start();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
            private void stopPlaying() {
                if(mPlayer != null) {
                    mPlayer.stop();
                    mPlayer.release();
                    mPlayer = null;
                }
            }
    
            OnCompletionListener completionListener = new OnCompletionListener() {
    
                @Override
                public void onCompletion(MediaPlayer mp) {
                    btnRecord.setEnabled(true);
                    btnPlay.setText("Start playing");
                    mStartPlaying = !mStartPlaying;
                }
            };
    
            OnErrorListener errorListenerForPlayer = new OnErrorListener() {
    
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Toast.makeText(getApplicationContext(), "Error during playing file", 3000).show();
                    return false;
                }
            };
    
            android.media.MediaRecorder.OnErrorListener errorListenerForRecorder = new android.media.MediaRecorder.OnErrorListener() {
    
                @Override
                public void onError(MediaRecorder mr, int what, int extra) {
                    Toast.makeText(getApplicationContext(), "Error during recoding file", 3000).show();
    
                }
            };
            /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                btnPlay = (Button)findViewById(R.id.btnPlay);
                btnRecord = (Button)findViewById(R.id.btnRecord);
                progress = (ProgressBar)findViewById(R.id.progressRecorder);
                mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
                mFileName += "/audiorecordtest.3gp";
                File file = new File(mFileName);
                if(!file.exists()) btnPlay.setEnabled(false); 
                btnPlay.setOnClickListener(this);
                btnRecord.setOnClickListener(this);
            }
    
            @Override
            protected void onPause() {
                super.onPause();
                if(mRecorder != null) {
                    mRecorder.stop();
                }
                if(mPlayer != null) {
                    mPlayer.pause();
                }
            }
    
    
            @Override
            protected void onResume() {
                super.onResume();
                if(mRecorder != null) {
                    mRecorder.start();
                }
                if(mPlayer != null) {
                    mPlayer.start();
                }
            }
    
            @Override
            protected void onStop() {
                super.onStop();
                if(mRecorder != null) {
                    mRecorder.stop();
                }
                if(mPlayer != null) {
                    mPlayer.stop();
                }
            }
    
            @Override
            protected void onDestroy() {
                super.onDestroy();
                if(mRecorder != null) {
                    mRecorder.release();
                    mRecorder = null;
                }
                if(mPlayer != null) {
                    mPlayer.release();
                    mPlayer = null;
                }
            }
    
            @Override
            public void onClick(View v) {
    
                if(v == btnPlay) {
    
                    onPlay(mStartPlaying);
                    if(mStartPlaying) {
                        duration = mPlayer.getDuration();
                        mThreadProgress = new ThreadProgress();
                        mThreadProgress.start();
                        ((Button)v).setText("Stop Playing");
                        btnRecord.setEnabled(false);
    
                    }
                    else {
                        ((Button)v).setText("Start Playing");
                        btnRecord.setEnabled(true);
                        if(mThreadProgress != null && !mThreadProgress.isAlive()) mThreadProgress.stop();
    
                        //  t.interrupt();
                    }
                    mStartPlaying = !mStartPlaying;
    
                } else if(v == btnRecord) {
                    onRecord(mStartRecording);
                    if(mStartRecording) {
                        mThreadProgress = new ThreadProgress();
                        mThreadProgress.start();
                        ((Button)v).setText("Stop Recording");
                        btnPlay.setEnabled(false);
                        //  t.start();
                    }
                    else {
                        ((Button)v).setText("Start Recording");
                        btnPlay.setEnabled(true);
                        //  t.interrupt();
                        if(mThreadProgress != null && !mThreadProgress.isAlive()) mThreadProgress.stop();
                    }
                    mStartRecording = !mStartRecording;
                }
            }
    
    
            Handler handler = new Handler(new Callback() {
    
                @Override
                public boolean handleMessage(final Message msg) {
                    if(msg.what == 0) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progress.setProgress(msg.arg1);
                            }
                        });
    
                    }
                    return false;
                }
            });
    
            public class ThreadProgress extends Thread implements Runnable {
    
                public int i = 0;
                @Override
                public void run() {
                    while((!this.isInterrupted() && mPlayer != null && mPlayer.isPlaying()) || (!this.isInterrupted() && mRecorder != null)) {
                        try {
                            if(duration == 1) i+=1;
                            else i += 100000 /duration;
                            Message message = new Message();
                            message.what = 0;
                            message.arg1 = i;
                            handler.sendMessage(message);
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }       
                    }
                }
    
            }
        }
    

    This is the example you can record audio as well as play audio

    You can store recorded file in following places
    1) File directory of your app
    2) External directory(SD card)
    3) Network