App Crash when stop recording second time - android

working in recording when i am record first time this working fine but second time is starting recording and when stop then recording then it crash nad give java.lang.IllegalStateException
i dont underswtand why
my code is
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String name = user.get(SessionManager.KEY_NAME);
String email = user.get(SessionManager.KEY_EMAIL);
// outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
_Start = (Button)findViewById(R.id.start);
_Stop =(Button)findViewById(R.id.stop);
_Send = (Button)findViewById(R.id.sendbtn);
_Play =(Button)findViewById(R.id.play);
_CountTimer =(TextView)findViewById(R.id.timer_view);
_ImgView =(ImageView)findViewById(R.id.imgView);
boolean exists = (new File(path)).exists();
if(!exists) {
new File(path).mkdirs();
}
else {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setOutputFile(path + audioname);
}
_CountTimer.setText("00:30");
final GumzoCounterClass timer = new GumzoCounterClass(30000, 1000);
_Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
try {
mRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mRecorder.start();
timer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
_ImgView.setVisibility(View.VISIBLE);
_Start.setVisibility(View.INVISIBLE);
_Play.setVisibility(View.INVISIBLE);
_Stop.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Start Recording", Toast.LENGTH_SHORT).show();
}
});
_Stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_ImgView.setVisibility(View.INVISIBLE);
_Start.setVisibility(View.VISIBLE);
_Stop.setVisibility(View.INVISIBLE);
_Play.setVisibility(View.VISIBLE);
mRecorder.stop();
timer.cancel();
_CountTimer.setText("Stoped Recording");
Toast.makeText(getApplicationContext(), "Stop Recording", Toast.LENGTH_SHORT).show();
}
});
_Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer m = new MediaPlayer();
// _Start.setEnabled(false);
try {
m.setDataSource(outputFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
} catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
public class GumzoCounterClass extends CountDownTimer {
public GumzoCounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
_CountTimer.setText("Completed");
mRecorder.stop();
mRecorder.release();
}
#Override
public void onTick(long millisUntilFinished) {
_CountTimer.setText((millisUntilFinished / 1000) + "");
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if(accessToken != null){
LoginManager.getInstance().logOut();
startActivity(new Intent(getApplicationContext(),Login_Activity.class));
finish();
}
Toast.makeText(MainActivity.this, "Logout User", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
My Logcate
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at user.example.com.myApp.MainActivity$2.onClick(MainActivity.java:95)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20262)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5631)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
help me please

Its because you are calling stop on a null object. You should check the state of your MediaRecorder before stopping

According to the official example from google you need to do the following when stop recording.
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
And releaseMediaRecorder() is look like,
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
// clear recorder configuration
mMediaRecorder.reset();
// release the recorder object
mMediaRecorder.release();
mMediaRecorder = null;
}
}

Related

How can I save multiple audio files?

I just started working on an audio recorder app. So far, the app can record audio and play it. My end goal is to be able to save multiple audio files to the device. How would I do this? Can I use SharedPreferences? I haven't been able to find anything.
public class MainActivity extends AppCompatActivity {
Button play;
Button stop;
Button record;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button3);
stop=(Button)findViewById(R.id.button2);
record=(Button)findViewById(R.id.button);
stop.setEnabled(false);
play.setEnabled(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(outputFile);
}
catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Create a folder in your external storage and store each file with a timestamp appended to the name of the file.
You can list all the video / audio files stored in this folder and select which video / audio you want to play anytime.
Get all files
public void displayAllFilesInFolder() {
List<String> filepath = new ArrayList<String>();
if (!hasSDCard()) {
return;
}
File dir = new File(android.os.Environment.getExternalStorageDirectory() + "folderName");
if (!dir.exists()) {
return;
}
File listAllFiles[] = dir.listFiles();
if (listAllFiles != null) {
for (int i = 0; i < listAllFiles.length; i++) {
if (!listAllFiles[i].isDirectory()) {
filepath.add(listAllFiles[i].getAbsolutePath());
}
}
}
}
Check if SD is mounted
private boolean hasSDCard(){
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent) {
return true;
}
else{
return false;
}
}
You're already saving it to a file:
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
You just need to add more logic to pick a filename that doesn't already exist.

Android - MediaRecorder start() throw IllegalStateException start-failed-2147483648

I am working on an App that requires recording a audio
Here's my partial code
private MediaRecorder myAudioRecorder;
private String outputFile = null;
private Button start, stop, play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
play = (Button) findViewById(R.id.button3);
stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrecording.3gp";;
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
public void start(View view) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
start.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();
}
The above code threw IllegalStateException. I have every permission entered in AndroidManifest.xml , I am very sure there's nothing wrong in AndroidManifest.xml.
I have read several solution but none of them working. How can I solve this problem?
public void stop(View view) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio Recorded successfully", Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void play(View view) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
MediaPlayer m = new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(getApplicationContext(), "Audio Playing", Toast.LENGTH_LONG).show();
}
}

MediaRecorder, getMaxAmplitude always returns 0

I have developed this small MediaRecorder application. I have 3 buttons- Play (for Start Recording), Pause (for stop recording), Max (for finding Max Amplitude). I Googled to get it correct, but nothing worked fine for me.
The problem is it always give me 0 for getMaxAmplitude.
Below is the code i am using. Can any one please help
public class MainActivity extends Activity {
Button play,pause, max;
String outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/myexampl.3gp";
MediaRecorder mrecorder=new MediaRecorder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id.button1);
pause= (Button)findViewById(R.id.button2);
max = (Button)findViewById(R.id.button3);
mrecorder = new MediaRecorder();
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mrecorder.setOutputFile(outputFile);
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
mrecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mrecorder.start();
Toast.makeText(getApplicationContext(), "Starts Recording!",
Toast.LENGTH_SHORT).show();
}
});
pause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
mrecorder.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mrecorder.release();
Toast.makeText(getApplicationContext(), "Stops Recording!",
Toast.LENGTH_SHORT).show();
}
});
max.setOnClickListener(new OnClickListener() {
int ampl=0;
#Override
public void onClick(View v) {
try {
ampl=mrecorder.getMaxAmplitude();
} catch (IllegalStateException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), String.valueOf(ampl),
Toast.LENGTH_SHORT).show();
}
});
}
#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;
}
}

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!

How to handle phone call while doing live audio streaming in android

I am doing an audio online streaming the audio is playing fine both in emulator and device. But the issue is when i make a call to my device simultaneously the streaming also playing. I need to pause and play the audio back while the call is coiming. Can u help how to handle that broadcasting.
public class BhajanStream extends Activity {
protected static final String TAG = null;
/** Called when the activity is first created. */
final String rs_bhajan_uri = "Media URL";
MediaPlayer mediaPlayer;
AudioManager audioManager;
Button bhajan_play;
Button bhajan_stop;
ImageView loadanim, effectbhajan;
AnimationDrawable loadanimation, effectanimation;
ProgressDialog dialog;
MusicServicePhoneStateListener mPhoneListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bhajan);
bhajan_play = (Button) findViewById(R.id.btn_play);
bhajan_stop = (Button) findViewById(R.id.btn_stop);
bhajan_stop.setVisibility(View.GONE);
loadanim = (ImageView) findViewById(R.id.loadeffectview);
effectbhajan = (ImageView) findViewById(R.id.bhajan_effect);
/*if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer= null;
}*/
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mediaPlayer.reset();
bhajan_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = conMan.getActiveNetworkInfo();
if (Info == null) {
Toast.makeText(BhajanStream.this, "POOR SIGNALS ",
Toast.LENGTH_LONG).show();
// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
loadanim.setBackgroundResource(R.drawable.loader_1);
loadanim.setBackgroundResource(R.anim.loadanim);
loadanimation = (AnimationDrawable) loadanim
.getBackground();
loadanimation.isVisible();
effectbhajan.setBackgroundResource(R.drawable.effect_bhajan1);
effectbhajan.setBackgroundResource(R.anim.bhajaneffect);
effectanimation = (AnimationDrawable) effectbhajan
.getBackground();
bhajan_play.setBackgroundResource(R.drawable.bhajan_start);
bhajan_play.setVisibility(View.GONE);
bhajan_stop.setVisibility(View.VISIBLE);
loadanim.setVisibility(View.VISIBLE);
effectbhajan.setVisibility(View.VISIBLE);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(rs_bhajan_uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
});
bhajan_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
bhajan_stop.setVisibility(View.GONE);
bhajan_play.setVisibility(View.VISIBLE);
mediaPlayer.stop();
loadanimation.stop();
effectanimation.stop();
loadanim.setVisibility(View.GONE);
effectbhajan.setVisibility(View.GONE);
}}
}
});
}
protected void onPreExecute() {
// UI work allowed here
loadanimation.start();
}
#Override
public void onBackPressed() {
// do something
if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
mediaPlayer.stop();
loadanimation.stop();
effectanimation.stop();
bhajan_stop.setVisibility(View.GONE);
bhajan_play.setVisibility(View.VISIBLE);
loadanim.setVisibility(View.GONE);
effectbhajan.setVisibility(View.GONE);
}
} else{
startActivity(new Intent(BhajanStream.this, SaiStreams.class));
finish();
}
}
private class MusicServicePhoneStateListener extends PhoneStateListener {
private boolean mResumeAfterCall = false;
#Override
public void onCallStateChanged(int state, String incoming_number) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
Log.i(TAG, "phone active, suspending music service");
mResumeAfterCall = mediaPlayer.isPlaying();
mediaPlayer.pause();
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.i(TAG, "phone inactive, resuming music service");
if (mResumeAfterCall) {
mediaPlayer.start();
}
break;
default:
break;
}
}
}
public void onCreate(){
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public void onDestroy(){
mPhoneListener = new MusicServicePhoneStateListener();
((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).listen(mPhoneListener, 0);
}
}
In your activity,you can register a phone state listener by calling public void listen (PhoneStateListener listener, int events) in the TelephonyManager class. See here. Also,You can call Context.getSystemService(Context.TELEPHONY_SERVICE) to get an instance of the TelephonyManager object.

Categories

Resources