I am trying to record the incoming voice call of the user.
My code is :
public class TService extends Service {
MediaRecorder recorder;
File audiofile;
String name, phonenumber;
String audio_format;
public String Audio_Type;
int audioSource;
Context context;
private Handler handler;
Timer timer;
Boolean offHook = false, ringing = false;
Toast toast;
Boolean isOffHook = false;
private boolean recordstarted = false;
private static final String ACTION_IN = "android.intent.action.PHONE_STATE";
private static final String ACTION_OUT = "android.intent.action.NEW_OUTGOING_CALL";
private CallBr br_call;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// final String terminate =(String)
// intent.getExtras().get("terminate");//
// intent.getStringExtra("terminate");
// Log.d("TAG", "service started");
//
// TelephonyManager telephony = (TelephonyManager)
// getSystemService(Context.TELEPHONY_SERVICE); // TelephonyManager
// // object
// CustomPhoneStateListener customPhoneListener = new
// CustomPhoneStateListener();
// telephony.listen(customPhoneListener,
// PhoneStateListener.LISTEN_CALL_STATE);
// context = getApplicationContext();
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
this.br_call = new CallBr();
this.registerReceiver(this.br_call, filter);
// if(terminate != null) {
// stopSelf();
// }
return START_NOT_STICKY;
}
#SuppressLint("InlinedApi")
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
#SuppressLint("InlinedApi")
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
{
if (wasRinging == true)
{
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/RenzymTest123");
if (!sampleDir.exists())
{
try
{
sampleDir.mkdirs();
}
catch(Exception e)
{
Log.d("make directory",e.toString());
}
}
out = out.replace(" ", "");
out = out.replace("-", "");
String file_name = "Recordaa";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
//recorder.reset();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
recorder.start();
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex)
{
ex.printStackTrace();
}
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
}
When I use this
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
I got exception while staring the recoder
Exception : java.lang.RuntimeException: start failed
I have searched on previosly asked asked questions but didnt find any solution
on link Android Media Recording: java.lang.RuntimeException: start failed
it says to use
recorder.setAudioSource(MediaRecorder.AudioSource.MIC); instead of voice call but records outing voice not incoming voice. How can I record incoming voice
An audio source of MIC should record incoming calls. You can set recording volume to the maximum level and turn on loudspeaker too as follows:
//before recording
AudioManager audioManager;
//turn on speaker
audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
//increase Volume
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0);
//start recording
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setAudioEncodingBitRate(320000);
recorder.setAudioSamplingRate(44100);
File audioFile = File.createTempFile("temp", "3gp", path);
recorder.setOutputFile(audioFile.getAbsolutePath());
recorder.prepare();
recorder.start();
Also there are other constants you can use with setAudioSource(), Just follow the guide to understand how each works
Related
First time when i run this code it runs fine but when i pause and play it again mainthread stop for more than or equal to 20 second and then show ANR dialog and after that it didn't start again.Reviewed this code many time but not able to debug.I also comment startRecording() and stopRecording() but after that it runs okay i.e, the problem is in starting and stopping the service.
public class RecordingService extends Service {
private String filePath = null;
private String dateSuffix = null;
private MediaRecorder mediaRecorder = null;
private DatabaseHelperClass databaseHelperClass;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
databaseHelperClass = new DatabaseHelperClass(getApplicationContext());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startRecording();
return START_STICKY;
}
#Override
public void onDestroy() {
stopRecording();
super.onDestroy();
}
private void stopRecording() {
try {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
}
catch (IllegalStateException e){
}
}
private void startRecording() {
if (mediaRecorder != null)
mediaRecorder.release();
pathCreater();
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioChannels(1);
mediaRecorder.setOutputFile(filePath);
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private void pathCreater() {
String fileName;
File file;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
long date = System.currentTimeMillis();
dateSuffix = simpleDateFormat.format(date);
do {
fileName = getString(R.string.file_name_suffix) + "_" + dateSuffix + ".mp3";
filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
filePath += "/" + fileName;
file = new File(filePath);
} while (file.exists() && !file.isDirectory());
}
}
I have been working on app that record calls in background. In my onReceive method i am trying to record incoming and outgoing call by using TelephonyManager and that works fine. but, Now I want to record calls in Seperate files when first call is running or answered and another call came and put first call on hold or something. I dont' know how to do that.
Somehow, this code record call only in one file.
Here is my Recording class
public class CallBr extends BroadcastReceiver {
Bundle bundle;
String state;
String inCall, outCall;
public boolean wasRinging = false;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (wasRinging == true) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record";
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
recordstarted = true;
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
if (recordstarted) {
recorder.stop();
recordstarted = false;
}
}
}
} else if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
Please, any help?
I am new in android development. When i am recording a call in my service class the recorder.start() is getting IllegalStateException.Here is my Logcat:
java.lang.IllegalStateException.android.media.MediaRecorder.stop(Native Method)
my serivce class is:--
public class RecordService extends Service {
private MediaRecorder recorder = null;
private String phoneNumber = null;
private String fileName;
private boolean onCall = false;
private boolean recording = false;
private boolean silentMode = false;
private boolean onForeground = false;
private int currentFormat = 0;
private String AUDIO_RECORDER_FOLDER = "Testing_recording";
String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP3,
AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };
static final String AUDIO_RECORDER_FILE_EXT_MP3 = ".mp3";
static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
MediaRecorder.OutputFormat.THREE_GPP };
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(Constants.TAG, "RecordService onStartCommand");
if (intent != null) {
int commandType = intent.getIntExtra("commandType", 0);
if (commandType != 0) {
if (commandType == Constants.RECORDING_ENABLED) {
Log.d(Constants.TAG, "RecordService RECORDING_ENABLED");
silentMode = intent.getBooleanExtra("silentMode", true);
if (!silentMode && phoneNumber != null && onCall
&& !recording)
commandType = Constants.STATE_START_RECORDING;
} else if (commandType == Constants.RECORDING_DISABLED) {
Log.d(Constants.TAG, "RecordService RECORDING_DISABLED");
silentMode = intent.getBooleanExtra("silentMode", true);
if (onCall && phoneNumber != null && recording)
commandType = Constants.STATE_STOP_RECORDING;
}
if (commandType == Constants.STATE_INCOMING_NUMBER) {
Log.d(Constants.TAG, "RecordService STATE_INCOMING_NUMBER");
startService();
if (phoneNumber == null)
phoneNumber = intent.getStringExtra("phoneNumber");
silentMode = intent.getBooleanExtra("silentMode", true);
} else if (commandType == Constants.STATE_CALL_START) {
Log.d(Constants.TAG, "RecordService STATE_CALL_START");
onCall = true;
if (phoneNumber != null && onCall
&& !recording) {
startService();
startRecording(intent);
}
} else if (commandType == Constants.STATE_CALL_END) {
Log.d(Constants.TAG, "RecordService STATE_CALL_END");
onCall = false;
phoneNumber = null;
stopAndReleaseRecorder();
recording = false;
stopService();
} else if (commandType == Constants.STATE_START_RECORDING) {
Log.d(Constants.TAG, "RecordService STATE_START_RECORDING");
if ( phoneNumber != null && onCall) {
startService();
startRecording(intent);
}
} else if (commandType == Constants.STATE_STOP_RECORDING) {
Log.d(Constants.TAG, "RecordService STATE_STOP_RECORDING");
stopAndReleaseRecorder();
recording = false;
}
}
}
return super.onStartCommand(intent, flags, startId);
}
/**
* in case it is impossible to record
*/
private void terminateAndEraseFile() {
Log.d(Constants.TAG, "RecordService terminateAndEraseFile");
stopAndReleaseRecorder();
recording = false;
// deleteFile();
}
private void stopService() {
Log.d(Constants.TAG, "RecordService stopService");
stopForeground(true);
onForeground = false;
this.stopSelf();
}
private void deletseFile() {
Log.d(Constants.TAG, "RecordService deleteFile");
FileHelper.deleteFile(fileName);
fileName = null;
}
private void stopAndReleaseRecorder() {
if (recorder == null)
return;
Log.d(Constants.TAG, "RecordService stopAndReleaseRecorder");
boolean recorderStopped = false;
boolean exception = false;
try {
recorder.stop();
recorderStopped = true;
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "IllegalStateException");
e.printStackTrace();
exception = true;
} catch (RuntimeException e) {
Log.e(Constants.TAG, "RuntimeException");
exception = true;
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
exception = true;
}
try {
recorder.reset();
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
exception = true;
}
try {
recorder.release();
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
exception = true;
}
recorder = null;
if (exception) {
// deleteFile();
}
if (recorderStopped) {
Toast toast = Toast.makeText(this,
this.getString(R.string.receiver_end_call),
Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onDestroy() {
Log.d(Constants.TAG, "RecordService onDestroy");
stopAndReleaseRecorder();
stopService();
super.onDestroy();
}
private void startRecording(Intent intent) {
Log.d(Constants.TAG, "RecordService startRecording");
boolean exception = false;
recorder = new MediaRecorder();
try {
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_UPLINK);
// recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// fileName = FileHelper.getFilename(phoneNumber);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
OnErrorListener errorListener = new OnErrorListener() {
public void onError(MediaRecorder arg0, int arg1, int arg2) {
Log.e(Constants.TAG, "OnErrorListener " + arg1 + "," + arg2);
terminateAndEraseFile();
}
};
recorder.setOnErrorListener(errorListener);
OnInfoListener infoListener = new OnInfoListener() {
public void onInfo(MediaRecorder arg0, int arg1, int arg2) {
Log.e(Constants.TAG, "OnInfoListener " + arg1 + "," + arg2);
terminateAndEraseFile();
}
};
recorder.setOnInfoListener(infoListener);
recorder.prepare();
// Sometimes prepare takes some time to complete
Thread.sleep(2000);
try {
recorder.start();
} catch (Throwable t) {
t.printStackTrace();
Log.w("sf", t);
}
// recorder.start();
/*new Handler().postDelayed(new Runnable() {
public void run() {
// recorder.stop();
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
System.out.println("hello helloo");
recorder = null;
}
Log.e("Ho rha hai", "goodndnd");
}
}, 40000);*/
recording = true;
Log.d(Constants.TAG, "RecordService recorderStarted");
Toast.makeText(getApplicationContext(), "recording is strated ", 2000).show();
} catch (IllegalStateException e) {
Log.e(Constants.TAG, "IllegalStateException");
e.printStackTrace();
exception = true;
} catch (IOException e) {
Log.e(Constants.TAG, "IOException");
e.printStackTrace();
exception = true;
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
exception = true;
}
if (exception) {
terminateAndEraseFile();
}
if (recording) {
Toast toast = Toast.makeText(this,
this.getString(R.string.receiver_start_call),
Toast.LENGTH_SHORT);
toast.show();
} else {
Toast toast = Toast.makeText(this,
this.getString(R.string.record_impossible),
Toast.LENGTH_LONG);
toast.show();
}
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
public void onError(MediaRecorder mr, int what, int extra) {
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
public void onInfo(MediaRecorder mr, int what, int extra) {
}
};
private void startService() {
if (!onForeground) {
Log.d(Constants.TAG, "RecordService startService");
Intent intent = new Intent(this, MainActivity.class);
// intent.setAction(Intent.ACTION_VIEW);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent pendingIntent = PendingIntent.getActivity(
getBaseContext(), 0, intent, 0);
Notification notification = new NotificationCompat.Builder(
getBaseContext())
.setContentTitle(
this.getString(R.string.notification_title))
.setTicker(this.getString(R.string.notification_ticker))
.setContentText(this.getString(R.string.notification_text))
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent).setOngoing(true)
.getNotification();
notification.flags = Notification.FLAG_NO_CLEAR;
startForeground(1337, notification);
onForeground = true;
}
}
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd_MMM_yy_HH_mm_ss");
String dateString = formatter.format(new Date(System
.currentTimeMillis()));
return (file.getAbsolutePath() + "/" + "Rec_" + dateString + file_exts[currentFormat]);
}
}
and broadcast receiver is this:--
public class MyPhoneReceiver extends BroadcastReceiver {
private String phoneNumber;
#Override
public void onReceive(Context context, Intent intent) {
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
String extraState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.d(Constants.TAG, "MyPhoneReciever phoneNumber "+phoneNumber);
if (MainActivity.updateExternalStorageState() == Constants.MEDIA_MOUNTED) {
try {
SharedPreferences settings = context.getSharedPreferences(
Constants.LISTEN_ENABLED, 0);
boolean silent = settings.getBoolean("silentMode", true);
if (extraState != null) {
if (extraState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Intent myIntent = new Intent(context,
RecordService.class);
myIntent.putExtra("commandType",
Constants.STATE_CALL_START);
context.startService(myIntent);
} else if (extraState
.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Intent myIntent = new Intent(context,
RecordService.class);
myIntent.putExtra("commandType",
Constants.STATE_CALL_END);
context.startService(myIntent);
} else if (extraState
.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
if (phoneNumber == null)
phoneNumber = intent
.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Intent myIntent = new Intent(context,
RecordService.class);
myIntent.putExtra("commandType",
Constants.STATE_INCOMING_NUMBER);
myIntent.putExtra("phoneNumber", phoneNumber);
myIntent.putExtra("silentMode", silent);
context.startService(myIntent);
}
} else if (phoneNumber != null) {
Intent myIntent = new Intent(context, RecordService.class);
myIntent.putExtra("commandType",
Constants.STATE_INCOMING_NUMBER);
myIntent.putExtra("phoneNumber", phoneNumber);
myIntent.putExtra("silentMode", silent);
context.startService(myIntent);
}
} catch (Exception e) {
Log.e(Constants.TAG, "Exception");
e.printStackTrace();
}
}
}
}
I want to create small app MediaRecord on smsreciver. when i recive message recording start and stop autometically . My problem is on sms recive recording is start but its never stop on next sms recive and my recorded file is successfully created but there is nothing inside. plz help
public class BroadCast extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SMSBroadcastReceiver";
private String recivedKey;
private MediaRecorder recorder;
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent recieved: " + intent.getAction());
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
if (messages.length > -1) {
if (messages[0].getOriginatingAddress() != null) {
if (recivedKey.equals(String.valueOf(record_key))) {
// Stop it being passed to the main Messaging
abortBroadcast();
startRecording();
SmsManager smsMgr = SmsManager.getDefault();
smsMgr.sendTextMessage(formattedNumber, null,
"Recording has been started, to stop recording any time send "
+ stop_record_key, null, null);
}
if (recivedKey.equals(String.valueOf(stop_record_key))) {
// Stop it being passed to the main Messaging
abortBroadcast();
stopRecording();
}
}
}
}
}
}
public void startRecording() {
System.out.println("STart Recording");
if (recorder != null) {
recorder.release();
} else {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
recorder.release();
}
}
}
private void stopRecording() {
System.out.println("Stop Recording");
try {
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
private String getFilename() {
File rootsd = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
if (!rootsd.isDirectory()) {
rootsd.mkdir();
}
File dcim = new File(rootsd+"/"+System.currentTimeMillis()+".3gp");
return dcim.getAbsolutePath();
}
}
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();
}
}