How to use getMaxAmplitude - Android

6.6k views Asked by At

I'm working on an App that can record en play audio using the MediaRecorder and MediaPlayer. I also want to display the value of the maxAmplitude. I tried to use the getMaxAmplitude but i cant get it work. it keeps returning 0. The recorder and the player are working properly (it's the from developer.android.com). Can someone please help me with it. Eventually i want to display the dB, but i think i can do that by myself once i got this working. I'm new to android/java, so every help is welcome.

my code

    public class AudioRecordTest extends Activity{
private static final String LOG_TAG = "AudioRecordTest";
protected static final String TAG = null;
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton   mPlayButton = null;
private MediaPlayer   mPlayer = null;
private int currentAmplitude;
public boolean activeThread;


private void onRecord(boolean start) {
    if (start) {
        startRecording();
    } else {
        stopRecording();
    }
}

private void onPlay(boolean start) {
    if (start) {
        startPlaying();
    } else {
        stopPlaying();
        }
}

private void startPlaying() {
    mPlayer = new MediaPlayer();
    try {
        mPlayer.setDataSource(mFileName);
        mPlayer.prepare();
        mPlayer.start();
    } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
}

private void stopPlaying() {
    mPlayer.release();
    mPlayer = null;
}

private void startRecording() {
    if (mRecorder == null) {

    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setOutputFile(mFileName);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    }

    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
    }

    mRecorder.start();


}

private void stopRecording() {
    mRecorder.stop();
    mRecorder.release();
    activeThread = true;
    mRecorder = null;
}


public void run() {
    // TODO Auto-generated method stub          
    try {
        activeThread = true;
        while(activeThread){
            Log.i(TAG, "onRun()" );
            Thread.sleep(50);
            threadHandler.sendEmptyMessage(0);

        }               
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

private Handler threadHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {

        currentAmplitude = mRecorder.getMaxAmplitude();
        Log.i(TAG, "handleMessage : MaxAmplitude : "+Integer.toString(currentAmplitude) );


    }

};

class RecordButton extends Button {
    boolean mStartRecording = true;

    OnClickListener clicker = new OnClickListener() {
        public void onClick(View v) {
            onRecord(mStartRecording);
            if (mStartRecording) {
                setText("Stop recording");
            } else {
                setText("Start recording");
            }
            mStartRecording = !mStartRecording;
        }
    };

    public RecordButton(Context ctx) {
        super(ctx);
        setText("Start recording");
        setOnClickListener(clicker);
    }
}

class PlayButton extends Button {
    boolean mStartPlaying = true;

    OnClickListener clicker = new OnClickListener() {
        public void onClick(View v) {
            onPlay(mStartPlaying);
            if (mStartPlaying) {
                setText("Stop playing");
            } else {
                setText("Start playing");
            }
            mStartPlaying = !mStartPlaying;
        }
    };

    public PlayButton(Context ctx) {
        super(ctx);
        setText("Start playing");
        setOnClickListener(clicker);
    }
}

public AudioRecordTest() {
    mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
    mFileName += "/audiorecordtest.3gp";
}

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    LinearLayout ll = new LinearLayout(this);
    mRecordButton = new RecordButton(this);
    ll.addView(mRecordButton,
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            0));
    mPlayButton = new PlayButton(this);
    ll.addView(mPlayButton,
        new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            0));
    TextView tv = new TextView(this);
    ll.addView(tv,
            new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                0));
    tv.setText(Integer.toString(currentAmplitude));
    setContentView(ll);
}

@Override
public void onPause() {
    super.onPause();
    if (mRecorder != null) {
        mRecorder.release();
        mRecorder = null;
    }

    if (mPlayer != null) {
        mPlayer.release();
        mPlayer = null;
    }
}

}

3

There are 3 answers

3
Jeremy D On

You should use Thread or Handler to be able to get the max amplitude value at different time. With your code, you actually called the getMaxAmplitude() method just after you start the MediaRecorder, and only once, so it is normal it will give you 0.

Here is some code I used to detect when the sound goes below a specific amplitude : http://pastebin.com/AradRpZm

1
Manuel Romero Rivera On

I'm using this code. I hope it works for you!

private MediaRecorder _recorder;
private MediaPlayer _player;
private Timer _timer;
private String _path;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_record);

    _timer = new Timer();
    prepareEvents();
}

public void prepareEvents() {
    try {
        Button recordButton = (Button) findViewById(R.id.buttonRecord);
        Button stopButton = (Button) findViewById(R.id.buttonStop);
        Button playButton = (Button) findViewById(R.id.buttonPlay);

        recordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(_recorder == null) {
                        File downloadFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS);
                        _path = downloadFolder.getAbsolutePath() + "/test1.aac";
                        _recorder = new MediaRecorder();
                        _recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        _recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
                        _recorder.setAudioSamplingRate(48000);
                        _recorder.setAudioEncodingBitRate(96000);
                        _recorder.setAudioChannels(2);
                        _recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                        _recorder.setOutputFile(_path);
                        _recorder.prepare();
                        _recorder.start();

                        _timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                RecordActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ((TextView) findViewById(R.id.textViewDecibelNumber)).setText(String.valueOf(_recorder.getMaxAmplitude()));
                                    }
                                });
                            }
                        },1000,1000);
                    }
                } catch(Exception exception) {}
            }
        });

        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(_recorder != null) {
                        _recorder.stop();
                        _recorder.release();
                        _recorder = null;
                        _timer.cancel();
                        ((TextView) findViewById(R.id.textViewDecibelNumber)).setText("0");
                    } else if(_player != null) {
                        _player.stop();
                        _player.release();
                        _player = null;
                    }
                } catch(Exception exception) {}
            }
        });

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(_recorder == null && _path != "") {
                        _player = new MediaPlayer();
                        _player.setDataSource(_path);
                        _player.prepare();
                        _player.start();
                    }
                } catch(Exception exception) {
                    System.out.println(exception.getMessage());
                }
            }
        });
    } catch(Exception exception) {
        System.out.println(exception.getMessage());
    }
}
0
Sara Zakizadeh On

I do this and it's OK for me. I hope it help you!

public class MediaRecorder{

private MediaRecorder mRecorder = null;
private Timer timer = new Timer();
File dir;
String file;

public Activity activity;

public void startRecording() {
    if (mRecorder == null) {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mRecorder.setOutputFile(getFilename());
        try {
            mRecorder.prepare();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mRecorder.start();
        mEMA = 0.0;
    }
}

public void stopRecording() {

    if (mRecorder != null) {
        mRecorder.stop();
        timer.cancel();
        timer.purge();
        mRecorder.release();
        mRecorder = null;
        deleteFile();
    }
}

private void deleteFile() {

    File sdcard = new File(file);
    boolean deleted = sdcard.delete();
    Log.i("Deleting File", String.valueOf(deleted));

}

@SuppressLint("SdCardPath")
private String getFilename() {
    dir = new File("/sdcard", "AUDIO_RECORDERING");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    file = dir.getAbsolutePath() + "/" + System.currentTimeMillis()
            + ".mp3";
    return (file);
}

private double getAmplitude() {
    if (mRecorder != null) {
        double m = mRecorder.getMaxAmplitude();
        return (m);
    } else {

        return 0;
    }
}

public double getAmplitudeEMA() {
    double amp = getAmplitude();
    return amp;
}

}