Java Question Java code error

gerredtor

Active Member
Licensed User
Hallo i become an error with a java code:

voiceRecordingVisualizer.java

B4X:
package ibe.libs.visualizer;

import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.Hide;
import anywheresoftware.b4a.BA.Permissions;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BA.Version;

@Version(1.00f)
@Permissions(values={"android.permission.RECORD_AUDIO"})
@ShortName("Visualizer")
public class voiceRecordingVisualizer implements RecordingSampler.CalculateVolumeListener {

    private BA ba;
    private String eventName;
    private RecordingSampler mRecordingSampler;



    public void Initialize(BA ba, String EventName) {
        _initialize(ba, null, EventName);
    }

    @Hide
    public void _initialize(BA ba, Object activityClass, String EventName) {
        this.eventName = EventName.toLowerCase(BA.cul);
        this.ba = ba;

        mRecordingSampler = new RecordingSampler();
        mRecordingSampler.setVolumeListener(this);
        mRecordingSampler.setSamplingInterval(100);
     }

    @Override
    public void onCalculateVolume(int volume) {
        // TODO Auto-generated method stub
      
    }
  
    public void toggleRecording() {
        if (mRecordingSampler.isRecording()) {
            mRecordingSampler.stopRecording();
        } else {
            mRecordingSampler.startRecording();
        }
    }
  
    public void releaseRecorder() {
        mRecordingSampler.release();
    }
  
    public int getD()
    {
        return mRecordingSampler.d;
    }
}

RecordingSampler.java

B4X:
package ibe.libs.visualizer;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioSource;
import android.util.Log;
import anywheresoftware.b4a.BA;

import java.util.Timer;
import java.util.TimerTask;

public class RecordingSampler {

    private static final int RECORDING_SAMPLE_RATE = 44100;

    private AudioRecord mAudioRecord;
    private boolean mIsRecording;
    private int mBufSize;

    private CalculateVolumeListener mVolumeListener;
    private int mSamplingInterval = 100;
    private Timer mTimer;
    public int d;
  
    private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
  
    public AudioRecord findAudioRecord() {
        BA.Log( "sdfsdf.sdfsdfsdfsdfsdfsdfsdf");
        for (int rate : mSampleRates) {
            BA.Log( "a");
            for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
                BA.Log( "b");
                for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
                    BA.Log( "c");
                    try {
                        BA.Log("Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
                                + channelConfig);
                        int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);

                        if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
                            // check if we can instantiate and have a success
                            AudioRecord recorder = new AudioRecord(AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);

                            if (recorder.getState() == AudioRecord.STATE_INITIALIZED) {
                                BA.Log( "asdasd.");
                                return recorder;
                            }else{
                                BA.Log( "d");
                            }
                      
                        }else{
                          
                            BA.Log( "kjlmt");
                        }
                    } catch (Exception e) {
                        BA.Log( rate + "Exception, keep trying.");
                    }
                }
            }
        }
        BA.Log( "sdfsdf.");
        return null;
    }

  
    public RecordingSampler() {
     //   init();
        mAudioRecord = findAudioRecord();
        mAudioRecord.release();
    }
  
    public void init()
    {
        //initAudioRecord();
        mAudioRecord = findAudioRecord();
        mAudioRecord.release();
    }

    /**
     * setter of CalculateVolumeListener
     *
     * @param volumeListener CalculateVolumeListener
     */
    public void setVolumeListener(CalculateVolumeListener volumeListener) {
        mVolumeListener = volumeListener;
    }

    /**
     * setter of samplingInterval
     *
     * @param samplingInterval interval volume sampling
     */
    public void setSamplingInterval(int samplingInterval) {
        mSamplingInterval = samplingInterval;
    }

    /**
     * getter isRecording
     *
     * @return true:recording, false:not recording
     */
    public boolean isRecording() {
        return mIsRecording;
    }

    private void initAudioRecord() {     
        int bufferSize = AudioRecord.getMinBufferSize(
                RECORDING_SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT
        );

        mAudioRecord = new AudioRecord(
                MediaRecorder.AudioSource.MIC,
                RECORDING_SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                bufferSize
        );

      
      
        if (mAudioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
            mBufSize = bufferSize;
        }
    }

    /**
     * start AudioRecord.read
     */
    public void startRecording() {
        mTimer = new Timer();
        mAudioRecord.startRecording();
        mIsRecording = true;
        runRecording();
    }

    /**
     * stop AudioRecord.read
     */
    public void stopRecording() {
        mIsRecording = false;
        mTimer.cancel();
    }

    private void runRecording() {
        final byte buf[] = new byte[mBufSize];
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                // stop recording
                if (!mIsRecording) {
                    mAudioRecord.stop();
                    return;
                }
                mAudioRecord.read(buf, 0, mBufSize);

                int decibel = calculateDecibel(buf);
                d = decibel;
                // callback for return input value
                if (mVolumeListener != null) {
                    mVolumeListener.onCalculateVolume(decibel);
                }
            }
        }, 0, mSamplingInterval);
    }

    private int calculateDecibel(byte[] buf) {
        int sum = 0;
        for (int i = 0; i < mBufSize; i++) {
            sum += Math.abs(buf[i]);
        }
        // avg 10-50
        return sum / mBufSize;
    }

    /**
     * release member object
     */
    public void release() {
        stopRecording();
        mAudioRecord.release();
        mAudioRecord = null;
        mTimer = null;
    }

    public interface CalculateVolumeListener {

        /**
         * calculate input volume
         *
         * @param volume mic-input volume
         */
        void onCalculateVolume(int volume);
    }
}

the error:

B4X:
** Service (starter) Start **
Error occurred on line: 17 (Starter)
java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
    at android.media.AudioRecord.startRecording(AudioRecord.java)
    at ibe.libs.visualizer.RecordingSampler.startRecording(RecordingSampler.java:134)
    at ibe.libs.visualizer.voiceRecordingVisualizer.toggleRecording(voiceRecordingVisualizer.java:44)
    at b4a.example.starter._service_start(starter.java:170)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:703)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:337)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:247)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:134)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:153)
    at b4a.example.starter.handleStart(starter.java:95)
    at b4a.example.starter.onStartCommand(starter.java:69)
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java)
    at android.app.ActivityThread.access$2200(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
    at android.os.Handler.dispatchMessage(Handler.java)
    at android.os.Looper.loop(Looper.java)
    at android.app.ActivityThread.main(ActivityThread.java)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
 
Top