How to record a call in android? - 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();
}
}

Related

Video streaming via socket

I need to implement video streaming via sockets in that I have to Record video on server side and Stream it live on client side, I have connected peers via socket successfully but video stream making trouble, I am facing following problems:
I have tested Media Recorder on API level 15 and 18 but not working on higher Android version, it's giving IllegalStateException start failed -38.
Media Player is not working, I have tried ParcelFileDescriptor to get the stream from socket and also tried to save the stream into a file to play on Media Player but I gained no outcome.
public class MainActivity2 extends Activity implements SurfaceHolder.Callback{
private Handler handler = new Handler();
private TextView text;
private EditText input, serverIP, port;
private Button send, connect;
private Socket socket;
private DataOutputStream outputStream;
private BufferedReader inputStream;
private String DeviceName = "Device", ipAddr;
Thread thread;
Integer portno;
private Handler handler2 = new Handler();
MediaPlayer mp;
private SurfaceView mPreview;
private SurfaceHolder holder;
VideoView mView;
SurfaceHolder mHolder;
// Video variable
MediaRecorder recorder, mMediaRecorder;
private Handler handler3 = new Handler();
boolean isRecording = false;
String AudioSavePathInDevice = null;
ParcelFileDescriptor pfd1;
Camera mCamera;
LocalServerSocket server;
LocalSocket sender;
private boolean searchNetwork() {
log("Connecting");
String ip = serverIP.getText().toString();
portno = Integer.parseInt(port.getText().toString());
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, portno), 100);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DeviceName += "1";
Log.i("Server", DeviceName);
log("Connected");
return true;
} catch (Exception e) {
}
return false;
}
private void runNewChatServer() {
ServerSocket serverSocket;
try {
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String myIP = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
serverSocket = new ServerSocket(portno);
log("I am ready to connect. Please enter the IP " + myIP + " in another device to connect...");
socket = serverSocket.accept();
DeviceName += "2";
log("another device Connected");
pfd1 = ParcelFileDescriptor.fromSocket(socket);
handler3.post(new Runnable() {
#Override
public void run() {
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mCamera.lock(); // take camera access back from MediaRecorder
// inform the user that recording has stopped
log("Stopped");
isRecording = false;
} else {
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
try {
mMediaRecorder.start();
// inform the user that recording has started
log("Started");
isRecording = true;
} catch (IllegalStateException e) {
log("IllegalStateException in media start " + e.getStackTrace());
e.printStackTrace();
} catch (NullPointerException e) {
log("NullException in media start " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
log("Exception in media start " + e.getMessage());
e.printStackTrace();
}
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
}
}
});
}
catch (Exception e) {
final String msg = e.getMessage();
log("Oops.Connection interrupted. Please reconnect your phones." + msg);
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
text = (TextView) findViewById(R.id.textin);
input = (EditText) findViewById(R.id.textout);
send = (Button) findViewById(R.id.send);
connect = (Button) findViewById(R.id.connect);
serverIP = (EditText)findViewById(R.id.serverip);
port = (EditText)findViewById(R.id.port);
mPreview = (SurfaceView) findViewById(R.id.surfaceView1);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mp = new MediaPlayer();
mView = (VideoView) findViewById(R.id.videoView);
mHolder = mView.getHolder();
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
thread = new Thread(new Runnable() {
#Override
public void run() {
try {
if (!searchNetwork()) {
runNewChatServer();
}
else
{
prepareMediaPlayer();
}
outputStream = new DataOutputStream(
socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
while (true) {
String Message = inputStream.readLine();
if (Message != null) {
log(Message);
}
}
} catch (IOException e) {
log("Error: IO Exception");
e.printStackTrace();
}
catch (Exception e) {
log("Error: Exception");
e.printStackTrace();
}
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (outputStream == null) {
return;
}
try {
String Message = input.getText().toString() + "\n";
outputStream.write(Message.getBytes());
log2(input.getText().toString());
} catch (IOException e) {
e.printStackTrace();
}
input.setText("");
}
});
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ipAddr = serverIP.getText().toString();
thread.start();
}
});
}
private void log(final String message) {
handler.post(new Runnable() {
String DeviceName2 = "";
#Override
public void run() {
if (DeviceName.equals("Device1")) {
DeviceName2 = "Device2";
} else if (DeviceName.equals("Device2")) {
DeviceName2 = "Device1";
} else {
DeviceName2 = "UnknowDevice";
}
text.setText(text.getText() + "\n" + DeviceName2 + " :"
+ message);
}
});
}
private void log2(final String message) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText(text.getText() + "\n" + "you" + " :"
+ message);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.exit(0);
return true;
}
return super.onKeyDown(keyCode, event);
}
private boolean prepareVideoRecorder(){
mMediaRecorder = new MediaRecorder();
mCamera = getCameraInstance();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
mMediaRecorder.setOutputFile(pfd1.getFileDescriptor());
// Step 5: Set the preview output
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
log("IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
log("IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
private boolean prepareMediaPlayer() {
try {
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
pfd.getFileDescriptor().sync();
mp.setDataSource(pfd.getFileDescriptor());
pfd.close();
mp.setDisplay(mHolder);
mp.prepareAsync();
mp.start();
return true;
}catch(Exception ex){
ex.printStackTrace();
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
Log.d("CameraInstance", e.getMessage());
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
public void surfaceCreated(SurfaceHolder holder) {
/* try {
prepareVideoRecorder();
} catch (IllegalStateException e) {
e.printStackTrace();
log("IllegalStateException preparing MediaRecorder2: " + e.getMessage());
finish();
}*/
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (isRecording) {
mMediaRecorder.stop();
isRecording = false;
}
releaseMediaRecorder();
releaseCamera();
finish();
}
}
I have also used these following code snippet to save the input stream into a file to play on Media Player but it didn't work for me.
File downloadingMediaFile = File.createTempFile("downloading", ".mp4");
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
IOUtils.copy(socket.getInputStream(), out);
mp.setDataSource(out.getFD());
I have tried this code snippet to Record the video stream on Lollipop or Higher API version but it's too didn't work.
ParcelFileDescriptor[] parcelFileDescriptors = new ParcelFileDescriptor[0];
try {
parcelFileDescriptors = ParcelFileDescriptor.createPipe();
} catch (IOException e) {
e.printStackTrace();
}
ParcelFileDescriptor parcelRead = new
ParcelFileDescriptor(parcelFileDescriptors[0]);
ParcelFileDescriptor parcelWrite = new
ParcelFileDescriptor(parcelFileDescriptors[1]);
mMediarecorder.setOutputFile(parcelWrite.fromSocket(socket).getFileDescriptor());

Android incoming call recording

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

How to record bluetooth headset audio?

I want to record audio from bluetooth headset. I search this and i find sources in this site about that. For example; How to record sound using bluetooth headset
Android MediaRecorder to AudioTrack, Recording and Playback
Text-To-Speech over bluetooth
public class MainActivity extends Activity {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private String outputFile = null;
private Button startBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private TextView text;
private AudioManager amanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
amanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
text = (TextView) findViewById(R.id.text1);
// store it to sd card
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/javacodegeeksRecording.3gpp";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stop(v);
}
});
playBtn = (Button)findViewById(R.id.play);
playBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
play(v);
}
});
stopPlayBtn = (Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopPlay(v);
}
});
}
public void start(View view){
try {
amanager.setMode(AudioManager.MODE_IN_CALL);
amanager.startBluetoothSco();
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text.setText("Recording Point: Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But program use in-built microphone. How can i use bluetooth headset audio?
Thanks.
As per android reference AudioManager.startBluetoothSco() start audio connection using startBluetoothSco() and stop android device speaker by using setSpeakerphoneOn(false). First connect your phone to device through bluetooth. Here is example for that.
Add permission "android.permission.MODIFY_AUDIO_SETTINGS" in manifest file.
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
System.out.println("ANDROID Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
/*
* Now the connection has been established to the bluetooth device.
* Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
* new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
*
* After finishing, don't forget to unregister this receiver and
* to stop the bluetooth connection with am.stopBluetoothSco();
*/
}
}
};
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
// Start Bluetooth SCO.
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothScoReceiver);
// Stop Bluetooth SCO.
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
}
Now start, stop and play audio based on requirement.
buttonStartRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Check audio permission
if (checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "AudioRecording.3gp";
// Start Media recorder
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStartRecording.setEnabled(false);
buttonStopRecording.setEnabled(true);
Toast.makeText(MainActivityOne.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
// Stop Media recorder
mediaRecorder.stop();
Toast.makeText(MainActivityOne.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
int selectedId = mRadioGroup.getCheckedRadioButtonId();
if (selectedId == R.id.radioButton) {
isAudioPlayInSameDevice = true;
} else {
isAudioPlayInSameDevice = false;
}
// if you want to play audio on your Mobile speaker then set isAudioPlayInSameDevice true
// and if you want to play audio to connected device then set isAudioPlayInSameDevice false.
if (isAudioPlayInSameDevice) {
audioManager.setMode(audioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(audioManager.MODE_NORMAL);
}
audioManager.setBluetoothScoOn(false);
audioManager.stopBluetoothSco();
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
// Start media player
System.out.println("Recorded Audio Path-" + AudioSavePathInDevice);
mediaPlayer.setDataSource(AudioSavePathInDevice);
if (isAudioPlayInSameDevice) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivityOne.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if (mediaPlayer != null) {
// Stop Media Player
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});
public void MediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
Click here to get the full source code.
To record from bluetooth you have to change the default phone Mic to headset Mic when recording starts this can be done by BluetoothSCO().
private static void startBluetoothRecording(
final OnBluetoothRecording BluetoothRecording,
final boolean resume, Context context) {
// TODO Auto-generated method stub
final int MAX_ATTEPTS_TO_CONNECT = 3;
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
final CountDownTimer timer = getTimer(BluetoothRecording, audioManager,
resume);
context.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(
AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
// cancel Timer
timer.cancel();
context.unregisterReceiver(this);
// pass through and true because
// recording from bluetooth so set 8000kHz
BluetoothRecording.onStartRecording(resume, true);
} else if (AudioManager.SCO_AUDIO_STATE_DISCONNECTED == state) {
if (count > MAX_ATTEPTS_TO_CONNECT) {
context.unregisterReceiver(this);
// Stop BluetoothSCO
audioManager.stopBluetoothSco();
// reset Counter
count = 0;
// stop timer
timer.cancel();
// false because still recording not started
BluetoothRecording.onStartRecording(resume, false);
} else {
// Increment Disconnect state Count
count++;
}
}
}
}, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));
// Start the timer
timer.start();
audioManager.startBluetoothSco();
}
For full class goto this link

How to email an audio file with the filepath in sdcard?

is there anyway I can send an email when I press the save button with OUTPUT_FILE path from sdcard. (I didn't implement the save button yet)
Should I change String to Uri instead to send an email?
I don't know how I should implement the save button making it to send an email with the audio file attached. Any suggestions? Thanks in advance!
public class FulfillAudioTaskActivity extends Activity {
private MediaPlayer mediaPlayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fulfill_audio_task);
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"/audiorecorder.3gpp";
}
public void buttonTapped(View view){
switch(view.getId()) {
case R.id.startBtn:
try {
beginRecording();
}catch (Exception e){
e.printStackTrace();
}
break;
case R.id.finishBtn:
try {
stopRecording();
} catch (Exception e){
e.printStackTrace();
}
break;
case R.id.playBtn:
try {
playRecording();
} catch (Exception e){
e.printStackTrace();
}
break;
case R.id.stopBtn:
try {
stopPlayback();
} catch (Exception e){
e.printStackTrace();
}
break;
}
}
private void stopPlayback() {
if(mediaPlayer != null)
mediaPlayer.stop();
}
private void playRecording() throws Exception{
ditchMediaPlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(OUTPUT_FILE);
mediaPlayer.prepare();
mediaPlayer.start();
}
private void ditchMediaPlayer() {
if(mediaPlayer != null)
{
try {
mediaPlayer.release();
}catch(Exception e){
e.printStackTrace();
}
}
}
// stop recording if there's a recorder running
private void stopRecording() {
if (recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception {
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
//check if there's a file already recorded, and if it is we want to get rid of it.
if(outFile.exists())
outFile.delete();
//create a new MediaRecorder object.
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
recorder.setOutputFile(OUTPUT_FILE);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
// TODO Auto-generated method stub
if(recorder != null)
recorder.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_fulfill_audio_task, menu);
return true;
}
}
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("audio/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] {"someone#gmail.com"} );
i.putExtra(Intent.EXTRA_SUBJECT, "MySubject");
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "audiorecorder.3gpp");
startActivity(i);
Hope this helps!

sound waves during recording in android

How to implement sound waves during recording sound in android??
in the below code
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultView = (TextView) findViewById(R.id.output);
try {
// the soundfile
File storageDir = new File(Environment
.getExternalStorageDirectory(), "com.hascode.recorders");
storageDir.mkdir();
Log.d(APP_TAG, "Storage directory set to " + storageDir);
outfile = File.createTempFile("hascode", ".3gp", storageDir);
// init recorder
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outfile.getAbsolutePath());
// init player
player.setDataSource(outfile.getAbsolutePath());
} catch (IOException e) {
Log.w(APP_TAG, "File not accessible ", e);
} catch (IllegalArgumentException e) {
Log.w(APP_TAG, "Illegal argument ", e);
} catch (IllegalStateException e) {
Log.w(APP_TAG, "Illegal state, call reset/restore", e);
}
btRecord = (Button) findViewById(R.id.btRecord);
btRecord.setOnClickListener(handleRecordClick);
btPlay = (Button) findViewById(R.id.btPlay);
btPlay.setOnClickListener(handlePlayClick);
}
private final OnClickListener handleRecordClick = new OnClickListener() {
#Override
public void onClick(View view) {
if (!recording) {
startRecord();
} else {
stopRecord();
}
}
};
private final OnClickListener handlePlayClick = new OnClickListener() {
#Override
public void onClick(View view) {
if (!playing) {
startPlay();
} else {
stopPlay();
}
}
};
private void startRecord() {
Log.d(APP_TAG, "start recording..");
printResult("start recording..");
try {
recorder.prepare();
recorder.start();
recording = true;
} catch (IllegalStateException e) {
Log
.w(APP_TAG,
"Invalid recorder state .. reset/release should have been called");
} catch (IOException e) {
Log.w(APP_TAG, "Could not write to sd card");
}
}
private void stopRecord() {
Log.d(APP_TAG, "stop recording..");
printResult("stop recording..");
recorder.stop();
recorder.reset();
recorder.release();
recording = false;
}
private void startPlay() {
Log.d(APP_TAG, "starting playback..");
printResult("start playing..");
try {
playing = true;
player.prepare();
player.start();
} catch (IllegalStateException e) {
Log.w(APP_TAG, "illegal state .. player should be reset");
} catch (IOException e) {
Log.w(APP_TAG, "Could not write to sd card");
}
}
private void stopPlay() {
Log.d(APP_TAG, "stopping playback..");
printResult("stop playing..");
player.stop();
player.reset();
player.release();
playing = false;
}
private void printResult(String result) {
resultView.setText(result);
}
Do you want to merge your recorded sound with a pre-recorded sound of waves?
If so, maybe you could try to create two sound objects of the different sources. Then you maybe could write to the output file in intervals. One interval for the pre-recorded and one for the fresh one.
I actually don't know if that's even a valid way to do this. Just what my general approach would've been facing this problem.

Categories

Resources