When I try to work it's show on textviev "0.0" value.
I get codes from this web site mostly
I get permissions to
<uses-permission android:name="android.permission.RECORD_AUDIO" />
ı give permission on setting-applications-mic
it's returned value "0.0"
how really works getAmplitude();
can some one explain
static final private double EMA_FILTER = 0.6;
TextView text;
Button buton;
Handler handler;
boolean state = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_karpuz_sec);
text = (TextView) findViewById(R.id.text);
buton = (Button) findViewById(R.id.button);
handler = new Handler();
buton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!state){
try {
start();
} catch (IOException e) {
e.printStackTrace();
}
}
else
stop();
}
});
}
Runnable runnable = new Runnable() {
#Override
public void run() {
while (!state){
text.setText(Double.toString(getAmplitudeEMA()));;
handler.postDelayed(this,100);
}
}
};
private MediaRecorder mRecorder = null;
private double mEMA = 0.0;
public void start() throws IOException {
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("/dev/null");
mRecorder.prepare();
mRecorder.start();
mEMA = 0.0;
state = true;
Toast.makeText(getApplicationContext(),"Ses Ölçümü Başladı",Toast.LENGTH_SHORT).show();
buton.setText("DURDUR");
text.setText(Double.toString(getAmplitudeEMA()));
}
}
public void stop() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
state = false;
Toast.makeText(getApplicationContext(),"Ses Ölçümü Durdu",Toast.LENGTH_SHORT).show();
buton.setText("BAŞLAT");
}
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude()/2700.0);
else
return 0;
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
return mEMA;
}
}
From MediaRecorder documentation, getMaxAmplitude() depicts :
Returns the maximum absolute amplitude that was sampled since the last call to this method. Call this only after the setAudioSource().
Returns : the maximum absolute amplitude measured since the last call, or 0 when called for the first time
This is why you get 0 the first time you call it in your onCreate().
Request it on a regular basis if you want as this is what suggests the presence of your Runnable, here is an example scheduling your getAmplitudeEMA() every 500ms :
private Timer mTimer = new Timer();
.....
mTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(Double.toString(getAmplitudeEMA()));
}
});
}
}, 0, 500);
And in stop() / onPause() :
mTimer.cancel();
mTimer.purge();
Related
I was referring to a code that I found previously and tried it myself. It works perfectly however the decibel measured from the code is extremely high even in a quiet room. The value ranged from 0 to 30000. I was expecting the decibel be around 30 ~ 40 when I am in a quiet room. Can someone please tell me what's wrong with the code? Maybe the algorithm in the code is wrong because "soundDB()" is not used. The decibel shown is the app is from "getAmplitudeEMA()" instead.
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class Noise extends Activity {
TextView mStatusView;
MediaRecorder mRecorder;
Thread runner;
private static double mEMA = 0.0;
static final private double EMA_FILTER = 0.6;
final Runnable updater = new Runnable(){
public void run(){
updateTv();
};
};
final Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noiselevel);
mStatusView = (TextView) findViewById(R.id.status);
if (runner == null)
{
runner = new Thread(){
public void run()
{
while (runner != null)
{
try
{
Thread.sleep(1000);
Log.i("Noise", "Tock");
} catch (InterruptedException e) { };
mHandler.post(updater);
}
}
};
runner.start();
Log.d("Noise", "start runner()");
}
}
public void onResume()
{
super.onResume();
startRecorder();
}
public void onPause()
{
super.onPause();
stopRecorder();
}
public void startRecorder(){
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("/dev/null");
try {
mRecorder.prepare();
}catch (java.io.IOException ioe) {
android.util.Log.e("[Monkey]", "IOException: " +
android.util.Log.getStackTraceString(ioe));
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " +
android.util.Log.getStackTraceString(e));
}
try{
mRecorder.start();
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " +
android.util.Log.getStackTraceString(e));
}
//mEMA = 0.0;
}
}
public void stopRecorder() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public void updateTv(){
mStatusView.setText(Double.toString((getAmplitudeEMA())) + " dB");
}
public double soundDb(double ampl){
return 20 * Math.log10(getAmplitudeEMA() / ampl);
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 0;
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
return mEMA;
}
}
The problem is the following line:
mStatusView.setText(Double.toString((getAmplitudeEMA())) + " dB");
You are setting as text the value returned from getAmplitudeEMA() but this is not a dB value, it's the amplitude returned by mRecorder.getMaxAmplitude() which is then modified by getAmplitudeEMA().
To "convert" amplitude to dB you need to include your soundDb(double ampl) method in this way:
public void updateTv(){
mStatusView.setText(Double.toString(soundDb(getAmplitudeEMA()))+ "dB");
}
You have to call the function soundDb, which transforms the amplitude into dB FS.
mStatusView.setText(soundDb(32767.0) + " dB");
I have a hard issue about audio recording in android. I used AudioTrack to play my sound when I speak to my phone. I want to record a part in my voice if i press button record. For example, I will speak within 10 seconds. However, I only want to record my sound iff I press record button. It can be from 3th second to 8th second. However, my phone need to play my sound during I speaking (from 1st to 10th second).
Currently, I used a thread to play my sound as following code. I created a flag in the recording thread to decide when I will record. When I press button record, the flag will be set true. And I click stop, It will set false and write to file
public class AudioSoundThread extends Thread {
private short[] audioBuffer;
private boolean isRecording = false;
private boolean isSounding = true;
private AudioRecordingHandler handler = null;
private AudioRecord record;
private AudioTrack track;
public AudioSoundThread(AudioTrack mtrack,AudioRecord mrecord,short[] maudioBuffer, AudioRecordingHandler handler) {
this.handler = handler;
this.audioBuffer = maudioBuffer;
this.record=mrecord;
this.track=mtrack;
}
#Override
public void run() {
record.startRecording();
DataOutputStream output =null;
if(isRecording){
output = prepareWriting();
if (output == null) { return; }
}
track.play();
///////////Play during recording
int readSize =0;
while (isSound) {
readSize=record.read(audioBuffer, 0, audioBuffer.length);
if ((readSize == AudioRecord.ERROR_INVALID_OPERATION) ||
(readSize == AudioRecord.ERROR_BAD_VALUE) ||
(readSize <= 0)) {
continue;
}
if(AudioRecord.ERROR_INVALID_OPERATION != readSize){
track.write(audioBuffer, 0, readSize);
}
if(isRecording)
write(output,readSize);
//Finished to write
if(!isRecording&&output!=null)
{
finishWriting(output);
File waveFile = getFile("wav");
try {
rawToWave(mRecording, waveFile);
deleteTempFile(mRecording);
} catch (IOException e) {
Log.e("Error writing file : ", e.getMessage());
}
}
}
record.stop();
record.release();
}
public synchronized void stopSound() {
isSound = false;
}
public synchronized void startSound() {
isSound = true;
}
public synchronized void startRecordingFlag() {
isRecording = true;
}
public synchronized void stopRecording() {
isRecording = false;
}
private void finishWriting(DataOutputStream out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
if (handler != null) {
handler.onRecordingError();
}
}
}
private DataOutputStream prepareWriting() {
if (mRecording.exists()) { mRecording.delete(); }
DataOutputStream out = null;
try {
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(mRecording)));
} catch (FileNotFoundException e) {
e.printStackTrace();
if (handler != null) {
handler.onRecordingError();
}
}
return out;
}
In mainActivity, I have two buttons that are play my sound and button recording
private AudioSoundThread recordingThread;
//Play button
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startSounding();
}
});
//Record button
btnRecord = (Button) findViewById(R.id.btnRecord);
btnRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//record();
recordingThread.startRecordingFlag();
}
});
//Stop Record button
btnStopRecord = (Button) findViewById(R.id.btnStopRecord);
btnStopRecord .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//record();
recordingThread.stopRecording();
}
});
private void startSounding() {
soundingThread = new AudioSoundThread(track,mRecorder,mBuffer,new AudioRecordingHandler() {
});
soundingThread.start();
}
However, my scheme does not work. I think that my flag cannot send to the thread. Could you look at my code and give me one solution?
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How to detect amplitude from user's voice?
Just detect if user speak or not.
What is the different between AudioRecorder, MediaRecorder, Audio Capture?
Please give me a full explanation and code please
i tried this class from tutorial but it has error in "mRecorder.prepare():"
import android.media.MediaRecorder;
public class SoundMeter {
static final private double EMA_FILTER = 0.6;
private MediaRecorder mRecorder = null;
private double mEMA = 0.0;
public void start() {
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.prepare();
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
mRecorder.start();
mEMA = 0.0;
}
}
public void stop() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude()/2700.0);
else
return 0;
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
return mEMA;
}
}
update my second try
public class MainActivity extends Activity {
static final private double EMA_FILTER = 0.6;
private MediaRecorder mRecorder = null;
private double mEMA = 0.0;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.start();
mEMA = 0.0;
tv = (TextView) findViewById(R.id.textView1);
double a = getAmplitude();
tv.setText(String.valueOf(a));
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
down();
}
}, 500, 10);
}
public void down() {
this.runOnUiThread(Update);
}
private Runnable Update=new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
double a = getAmplitude();
tv.setText(String.valueOf(a));
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 0;
}
}
A couple of things:
You need to set Output Format before the prepare() statement. From the documentation for prepare(): Throws IllegalStateException if it is called after start() or before setOutputFormat()
MediaRecorder.prepare() also throws IOException. You may want to surround the prepare() with a try/catch construct.
try:
if (mRecorder == null) {
try {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
mRecorder.prepare();
mRecorder.start();
mEMA = 0.0;
}
catch (IOException e) {
//do something with e
}
}
Currently my Code is detecting voice intensity (using media recorder) i want to change background color to white when there is no voice , when user speak then background color must b light or dark according to voice intensity
here is my code im having problem to make color light and dark according to voice intensity .
final Runnable updater = new Runnable(){
public void run(){
updateTv();
TextView tv = (TextView)findViewById(R.id.status);
int tvStatus= Integer.parseInt(tv.getText().toString());
if(tvStatus > 1000)
updateBackground();
else
mScreen.setBackgroundColor(Color.WHITE);
};
};
final Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mStatusView = (TextView) findViewById(R.id.status);
mScreen = (LinearLayout) findViewById(R.id.myScreen);
if (runner == null)
{
runner = new Thread(){
public void run()
{
while (runner != null)
{
try
{
Thread.sleep(1000);
Log.i("Noise", "Tock");
} catch (InterruptedException e) { };
mHandler.post(updater);
}
}
};
runner.start();
Log.d("Noise", "start runner()");
}
}
private void updateBackground()
{
int ampl =(int)getAmplitude();
int color;
Random rnd = new Random();
mScreen.setBackgroundColor(
color );
}
public void onResume()
{
super.onResume();
startRecorder();
}
public void onPause()
{
super.onPause();
stopRecorder();
}
public void startRecorder(){
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("/dev/null");
try
{
mRecorder.prepare();
}catch (java.io.IOException ioe) {
android.util.Log.e("[Monkey]", "IOException: " + android.util.Log.getStackTraceString(ioe));
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " + android.util.Log.getStackTraceString(e));
}
try
{
mRecorder.start();
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " + android.util.Log.getStackTraceString(e));
}
//mEMA = 0.0;
}
}
public void stopRecorder() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public void updateTv(){
mStatusView.setText(Integer.toString((getAmplitude())));
}
public double soundDb(double ampl){
return 20 * Math.log10(getAmplitudeEMA() / ampl);
}
public int getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 0;
}
Your current implementation of updateBackground() uses color without initializing it:
private void updateBackground() {
int ampl = (int) getAmplitude();
int color;
Random rnd = new Random();
mScreen.setBackgroundColor(color);
}
If the minimum amplitude is 0 and the maximum amplitude is MAX_AMPLITUDE, and if you want white to represent minimum amplitude, and black, maximum amplitude, then something like this should do the trick:
private static final int MAX_RGB = 255;
private static final int MAX_AMPLITUDE = 32767;
private void updateBackground() {
float amplF = (float) getAmplitude();
int ampl = MAX_RGB - (int) (amplF / MAX_AMPLITUDE * MAX_RGB);
mScreen.setBackgroundColor(Color.rgb(ampl, ampl, ampl));
}
If you find that the highest amplitude values you see in practice are significantly lower than 32767, you can account for this with:
private static final int MAX_RGB = 255;
private static final int int MAX_AMPLITUDE = 1500; // Set to some reasonable value
private void updateBackground() {
int actual = getAmplitude();
if (actual > MAX_AMPLITUDE)
actual = MAX_AMPLITUDE;
float amplF = (float) actual;
int ampl = MAX_RGB - (int) (amplF / MAX_AMPLITUDE * MAX_RGB);
mScreen.setBackgroundColor(Color.rgb(ampl, ampl, ampl));
}
If you do that, it would probably be a good idea to make MAX_AMPLITUDE no longer a constant, and make it configurable by offering a "calibrate" option, where users can make whatever they consider to be a loud noise.
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;
}
}
}
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());
}
}
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
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;
}
}