0

I am trying to record audio with different frequency. Though I have been trying to implement it by the following code but its not working (app unexpectedly stopped).

//importing packages    
        import android.app.Activity;
        import android.media.AudioFormat;
        import android.media.AudioRecord;
        import android.media.MediaRecorder;
        import android.os.Bundle;
        import android.os.Environment;
        import android.view.KeyEvent;
        import android.view.View;
        import android.widget.Button;

        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;

    public class MainActivity extends Activity {
        private static final int RECORDER_SAMPLERATE = 44100;
        private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
        private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
        private AudioRecord recorder = null;
        private Thread recordingThread = null;
        private boolean isRecording = false;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setButtonHandlers();//handling buttons
            enableButtons(false);

            int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                    RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
        }
        private void setButtonHandlers() {
            ((Button) findViewById(R.id.Start)).setOnClickListener(btnClick);
            ((Button) findViewById(R.id.Stop)).setOnClickListener(btnClick);
        }

        private void enableButton(int id, boolean isEnable) {
            ((Button) findViewById(id)).setEnabled(isEnable);
        }

        private void enableButtons(boolean isRecording) {
            enableButton(R.id.Start, !isRecording);
            enableButton(R.id.Stop, isRecording);
        }

        int BufferElements2Rec = 1024;  // want to play 2048 (2K) since 2 bytes we use only 1024
        int BytesPerElement = 2;  // 2 bytes in 16bit format

        public void Record()
        {
            recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                    RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                    RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

            recorder.startRecording();
            isRecording = true;
            recordingThread = new Thread(new Runnable() {
                public void run() {
                    writeAudioDataToFile();
                }
            }, "AudioRecorder Thread");
            recordingThread.start();

        }
        private byte[] short2byte(short[] sData) {
            int shortArrsize = sData.length;
            byte[] bytes = new byte[shortArrsize * 2];
            for (int i = 0; i < shortArrsize; i++) {
                bytes[i * 2] = (byte) (sData[i] & 0x00FF);
                bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
                sData[i] = 0;
            }
            return bytes;

        }
        private void writeAudioDataToFile() {
          // Write the output audio in byte

            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/myrec.pcm";
            short sData[] = new short[BufferElements2Rec];

            FileOutputStream os = null;
            try {
                os = new FileOutputStream(filePath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            while (isRecording) {
               // gets the voice output from microphone to byte format

                recorder.read(sData, 0, BufferElements2Rec);
                System.out.println("Short wirting to file" + sData.toString());
                try {
                   // // writes the data to file from buffer
                   // // stores the voice buffer
                    byte bData[] = short2byte(sData);
                    os.write(bData, 0, BufferElements2Rec * BytesPerElement);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void Record_Stop()
        {
            if (null != recorder) {
                isRecording = false;
                recorder.stop();
                recorder.release();
                recorder = null;
                recordingThread = null;
            }
        }
        private View.OnClickListener btnClick = new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.Start: {
                        enableButtons(true);
                        Record();
                        break;
                    }
                    case R.id.Stop: {
                        enableButtons(false);
                        Record_Stop();
                        break;
                    }
                }
            }
        };

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                finish();
            }
            return super.onKeyDown(keyCode, event);
        }
    }

As soon as I press the start button the app gets unexpectedly stopped.

com.example.kaushal.learningfft E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.kaushal.learningfft, PID: 4705 java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord. at android.media.AudioRecord.startRecording(AudioRecord.java:97‌​6) at com.example.kaushal.learningfft.MainActivity.Record(MainActi‌​vity.java:57) at com.example.kaushal.learningfft.MainActivity$2.onClick(MainA‌​ctivity.java:126) at android.view.View.performClick(View.java:5610) at android.view.View$PerformClick.run(View.java:22265) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(Z‌​ygoteInit.java:865) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

VC.One
  • 14,790
  • 4
  • 25
  • 57
  • at android.view.View.performClick(View.java:5610) at android.view.View$PerformClick.run(View.java:22265) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) – Kaushal Agarwal Apr 21 '17 at 12:14
  • com.example.kaushal.learningfft E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.kaushal.learningfft, PID: 4705 java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord. at android.media.AudioRecord.startRecording(AudioRecord.java:976) at com.example.kaushal.learningfft.MainActivity.Record(MainActivity.java:57) at com.example.kaushal.learningfft.MainActivity$2.onClick(MainActivity.java:126) – Kaushal Agarwal Apr 21 '17 at 14:49
  • after this my old comment post follows – Kaushal Agarwal Apr 21 '17 at 14:50
  • Nandsito was correct on his/her (now deleted) question - this was getting rather broad. Stack Overflow readers will be happy to help but they will not supply "a better code", that would be doing your work for you. – halfer Apr 22 '17 at 08:54
  • Would you move your crash logs into the question itself? Comments are not to be used for critical parts of the question, they are just for discussions to help with clarification. – halfer Apr 22 '17 at 08:55
  • sorry for my the inconvenience as i m new to stack overflow site... – Kaushal Agarwal Apr 22 '17 at 12:40
  • You can't mix _"different frequency"_ in audio file. Decide on one frequency (sample rate) and make a file from that. The error tells you that Function `startRecording()` called an un-initialized `AudioRecord` var. Nothing about frequencies... Anyways check [**this Answer**](http://stackoverflow.com/a/5440517/2057709) and read all comments and other Answers on that page. Maybe something useful to you in them. – VC.One Apr 28 '17 at 17:07

0 Answers0