Lag on my buttons - android

I made a code which allow me to record the audio from the microphone. Strange thing is that when I click my button it appears to have some kind of lag, the button remains visually pressed for half a second and then starts it method. is there a reason for this, and how could I solve this?
What I am having right now:
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void startRecording() {
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();
mRecorder = null;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRecord:
if (mStartRecording) {
mRecordButton.setText("Stop Recording");
onRecord(true);
mStartRecording = false;
} else {
mRecordButton.setText("Start Recording");
mStartRecording = true;
onRecord(false);
}
break;
}
EDIT
Thanks for the help, I decided to work with a service but am struggling a little bit. I created:
public class RecordService extends IntentService {
private MediaRecorder mRecorder = null;
private String mFileName;
private static final String LOG_TAG = "RecordService";
public RecordService() {
super("RecordService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
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();
}
}
and
case R.id.bRecord:
if (mStartRecording) {
mRecordButton.setText("Stop Recording");
//onRecord(true);
Intent service = new Intent(myContext, RecordService.class);
myContext.startService(service);
mStartRecording = false;
} else {
mRecordButton.setText("Start Recording");
mStartRecording = true;
onRecord(false);
}
break;
Having a question about this, how can I now stop this service (= stop recording) (by clicking f.e. the button again) and communicate an idea back to the activity? I tried to add a stop function in the service but it is not seem to work when I call service.stop() to stop it..

My guess is that since you're starting the recording in the same thread as the UI, the UI doesn't respond until all the code in startRecording() has finished executing. You might want to consider calling onRecord in its own thread.

You could use AsyncTask for short Operations (a few seconds at the
most.)
Use Service for long running Operations
Attention: AsyncTask takes care of the thread handling for you. If you write a Service, you have to spawn your own thread otherwise it will run on the UI thread.
One of several ways to do it:
Service:
#Override
protected void onHandleIntent(Intent intent) {
//your recorder code
//get the messenger from intent
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
try {
//send a message back to the activity
messenger.send(...);
} catch (android.os.RemoteException e1) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
Activity:
Definition of the handler
private Handler handler = new Handler() {
public void handleMessage(Message message) {
//do something with the message from the service
};
};
The code to start the service
Intent intent = new Intent(this, YourService.class);
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
startService(intent);

Related

Voice recording program on android studio with Java

My Code:
public class MainActivity extends AppCompatActivity {
private Button mRecordBtn;
private TextView mRecordLabel;
private MediaRecorder mRecorder;
private String mFileName = null;
private static final String LOG_TAG = "Record_log";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecordLabel = (TextView) findViewById(R.id.recordLabel);
mRecordBtn = (Button) findViewById(R.id.recordBtn);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName = "/recorded_audio.3gp";
mRecordBtn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN ){
startRecording();
mRecordLabel.setText("Recording in Progress");
}
else if (motionEvent.getAction() == MotionEvent.ACTION_UP){
stopRecording();
mRecordLabel.setText("Recording Stopped");
}
return false;
}
});
}
private void startRecording() {
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(); //I am getting a bug on this line
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
when I ran this code on my Samsung Galaxy s7 edge, as well as on the nexxus 7 emulator given by android studio the app crashes. I posted all of the code because im not sure exactly where its messing up. It crashes when I press the button. It as made to be a press and hold to record, and release to stop recording
Check if the issue is with permission recording audio.

How to record audio file using timer

Hi i am new for android and in my app i have to record audio using timer as like my below image, Using my below i can able record audio but how can do this scenario with help of timer please help me some
My code:-
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.record_button:
startRecording()
break;
case R.id.stop_button:
break;
}
}
private void startRecording() {
try {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.prepare();
mRecorder.start();
} catch (Throwable t) {
t.printStackTrace();
}
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
Just start a timer in startRecording and stop it in stopRecording. See: https://stackoverflow.com/a/3734070/2324204
You can use a Chronometer which already exists in Android.
Note: Chronometer is a widget that extends TextView so replace your current TextView with the Chronometer.
Example with your code would be:
//....
Chronometer simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer);
//...
private void startRecording() {
try {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.prepare();
mRecorder.start();
simpleChronometer.start(); // start a chronometer
//simpleChronometer.setFormat("Time Running - %s"); // set the format for a chronometer
} catch (Throwable t) {
t.printStackTrace();
}
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
simpleChronometer.stop();
}
In case you want to do things manually you can use the Stopwatch class.

Media Recorder Strange Behavior in Service

I'm starting a Service for recording voice with mice. It runs successfully because it shows notification and toast in OnCreate of service. But the control never reach on the mediaRecorder.prepare try block and it don't even show my toast in the catch block.
Here is my AudioRecorder Service
public class ServiceBgAudioRecorder extends Service {
public static boolean isRecording = false;
public static MediaRecorder mediaRecorder;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this,"Oncreate of service",Toast.LENGTH_LONG).show();
startRecording();
}
private void startRecording() {
Notification notification = new Notification.Builder(this)
.setContentTitle("Background Audio Recorder" )
.setContentText("Audio recording is started")
.setSmallIcon(R.drawable.appicon)
.build();
startForeground(1234, notification);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFile(AppUtilities.getOutputMediaFile(AppUtilities.MEDIA_TYPE_3GP).getAbsolutePath());
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mediaRecorder.prepare();
mediaRecorder.start();
Toast.makeText(this,"Audio Recording is started",Toast.LENGTH_LONG);
isRecording = true;
} catch (IOException e) {
Toast.makeText(this,"Can't start Audio Recording",Toast.LENGTH_LONG);
}
}
private void stopRecording() {
mediaRecorder.release();
mediaRecorder = null;
isRecording = false;
}
#Override
public void onDestroy() {
stopRecording();
}
}
I don't know why the control is not reaching in try/catch block.
You need to display the toast ?
append show() method to the makeText().
Toast.makeText(getActivity(),"Audio Recording is started",Toast.LENGTH_LONG).show();

Audio recorder restarting

I've create Audio recorder. When rotating my device the audio will be automatically saved. How can I avoid this ? I'm using Android 4.1.1 on device.
private MediaRecorder mRecorder = null;
private static final String LOG_TAG = "MediaAudioCapture";
ImageButton button_audio_button = (ImageButton) findViewById(R.id.audio_button);
button_audio_button.setOnClickListener(new OnClickListener() {
public void onClick(View record_button) {
ImageButton audio_button = (ImageButton) record_button;
if (!started_note_recording) {
if (!started_recording) {
startRecording();
audio_button.setImageResource(R.drawable.audio_red);
} else {
stopRecording();
audio_button.setImageResource(R.drawable.audio);
}
}
}
});
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(output.getAbsolutePath());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
ImageButton button_audio_button = (ImageButton)findViewById(R.id.audio_button);
button_audio_button.setImageResource(R.drawable.audio);
}
}
});
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
stopWatch.start();
}
That's because when you rotate, activity will be reload. You can fix the orientation to portrait or you have to change your logic to retain the state on rotation.

How to record a call in android?

Recorder = new MediaRecorder();
Recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
Recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
Recorder.setOutputFile(FileName);
Recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
this is my Code and i am not able to record the voice of other person.so what should i use instead of AudioSorce.MIC.
plz help me
Sorry to disappoint you, but you can't, not in the general case. Most Android running phones have the wiring in hardware/firmware so that the media of the call does not pass through the application processor at all - it goes from the audio to the DSP and vice versa, so you cannot access it.
You can catch the audio of the person using the phone, but not the other way around, disregarding silly hacks like asking the person to use the speakers and recording the sound from there via the phone mic...
class MyPhoneStateListener extends PhoneStateListener implements SensorEventListener {
Context context;
AudioManager audioManager;
MediaRecorder recorder;
private SensorManager mSensorManager;
private Sensor myLightSensor;
private boolean CallState;
private float sensorState;
public MyPhoneStateListener(Context context) {
this.context = context;
mSensorManager = (SensorManager) this.context.getSystemService(Context.SENSOR_SERVICE);
myLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
audioManager = (AudioManager) this.context.getSystemService(Context.AUDIO_SERVICE);
if (myLightSensor == null){
Log.i("On Receive", "Not Support");
}else{
mSensorManager.registerListener(this,myLightSensor,SensorManager.SENSOR_DELAY_NORMAL);
}
}
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
System.out.println("My Call IDLE");
CallState = false;
StartAudioSpeacker();
StopRecording();
System.out.println("Is phone speaker : "+ audioManager.isSpeakerphoneOn());
if (audioManager.isSpeakerphoneOn()) {
audioManager.setSpeakerphoneOn(false);
mSensorManager.unregisterListener(this);
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
System.out.println("My Call OFFHOOK");
CallState = true;
StartAudioSpeacker();
StartRecording();
System.out.println("Is phone speaker : "+ audioManager.isSpeakerphoneOn());
break;
case TelephonyManager.CALL_STATE_RINGING:
System.out.println("My Call RINGING");
break;
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
if (sensor.getType() == Sensor.TYPE_PROXIMITY) {
Log.i("Sensor Changed", "Accuracy :" + accuracy);
}
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
Log.i("Sensor Changed", "onSensor Change :" + event.values[0]);
sensorState = event.values[0];
StartAudioSpeacker();
}
}
public void StartAudioSpeacker(){
if (CallState && sensorState == 1.0) {
audioManager = (AudioManager) this.context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
audioManager.setStreamVolume(AudioManager.MODE_IN_CALL, audioManager.getStreamMaxVolume(AudioManager.MODE_IN_CALL), 1);
System.out.println("Is phone speaker : "+ audioManager.isSpeakerphoneOn());
}else{
audioManager = (AudioManager) this.context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(false);
audioManager.setStreamVolume(AudioManager.MODE_IN_CALL, audioManager.getStreamMaxVolume(AudioManager.MODE_IN_CALL), 1);
System.out.println("Speaker Volume :"+ audioManager.getStreamMaxVolume(AudioManager.MODE_IN_CALL));
System.out.println("Is phone speaker : "+ audioManager.isSpeakerphoneOn());
}
}
public void StartRecording(){
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(this.getFullSdPath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.start(); // Recording is now started
Log.i(this.getClass().getName(), "Start Recording");
}
public void StopRecording(){
recorder.stop();
recorder.reset();
recorder.release();
Log.i(this.getClass().getName(), "Stop Recording");
}
public String getFullSdPath(){
File sdCard = new File(Environment.getExternalStorageDirectory() + "/RecordMyVoice");
if (!sdCard.exists()) {
sdCard.mkdir();
}
File file = new File(Environment.getExternalStorageDirectory()+"/RecordMyVoice/",new Date().getTime()+".3gp");
System.out.println("Full path of record sound is : "+file.getAbsolutePath());
return file.getAbsolutePath();
}
}
As I known and I have finshed this kind of job.I mean both the user's voice and the other people's voice.We used the customized ROM of one phone provided by the specificated factory and they also have modificated some security mechanism of the ROM.Another way you can try this:
https://github.com/FR13NDS/call-recorder-for-android
Try This code to record call.
AudioManager audioManager;
private MediaRecorder myAudioRecorder;
//Myservice m=new Myservice();
private String outputFile = null;
String uid=null;
String no=null;
String rname=null;
public void record(Context c,String no, String ser){
try{
this.no=no;
uid=ser;
rname=String.format("%d.mp3", System.currentTimeMillis());
//rname="/#"+uid+"#"+rname;
outputFile = Environment.getExternalStorageDirectory().toString() + "/Android/free"+"/#"+uid+"#"+no+"#"+rname;
StartAudioSpeacker();
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}catch(IllegalStateException e){e.printStackTrace();}
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getc(Context c) {
// TODO Auto-generated method stub
this.c=c;
}
public void st()
{ //Toast.makeText(;, "recorded",Toast.LENGTH_LONG).show();
try{
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder=null;
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
Handler h=new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try{
uprecord ur=new uprecord("/#"+uid+"#"+no+"#"+rname);
ur.tt();
}catch(IllegalStateException e){e.printStackTrace();} }
}, 1000);
}
public void StartAudioSpeacker(){
audioManager = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(false);
audioManager.setStreamVolume(AudioManager.MODE_IN_CALL, audioManager.getStreamMaxVolume(AudioManager.MODE_IN_CALL), 1);
System.out.println("Speaker Volume :"+ audioManager.getStreamMaxVolume(AudioManager.MODE_IN_CALL));
System.out.println("Is phone speaker : "+ audioManager.isSpeakerphoneOn());
}
}
I didnt try it on Phone, but according doc MediaRecorder.AudioSource you should use
MediaRecorder.AudioSource.VOICE_CALL
instead of
MediaRecorder.AudioSource.MIC
Hopes that works
If you are trying to store the audio file to sdcard, try this code. It will work fine.
protected void startRecording() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
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();
}
}

Categories

Resources