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

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();
}
}

Related

App Crash when stop recording second time

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;
}
}

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.

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;
}
}

Media Recorder Start Failed-22 inside a thread

Hi i am trying to make a video recorder android app> For some reason i need to get its audio, i have tried some libraries but nothing really extracted me the audio. So now my approach is that instead of using native libraries can i record video and audio separately? Main thread records video and another thread records audio. I am getting error when i call start() method of media recorder class inside thread and i get Start Failed -22. Following is my code.
public class MainActivity extends Activity {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec ;
ImageView recordingBt;
public MediaRecorder mrec2 = new MediaRecorder();
File video;
private Camera mCamera;
File audiofile = null;
File audiofile2 = null;
boolean recording=false;
TextView tv;
View myview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recordingBt= (ImageView) findViewById(R.id.camera);
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
tv=(TextView) findViewById(R.id.textView1);
myview = findViewById(R.id.MyBigView);
}
#Override
protected void onStart(){
super.onStart();
Log.i("Recording Activity", "we are inside Start function of Recording Activity");
Log.i("Recording Activity", "Opening camera");
mCamera = Camera.open();
Log.i("Recording Activity", "Camera Opened");
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
recordingBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(recording==false){
try {
Log.i("Recording Activity", "Recording Start");
startRecording();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
stopRecording();
}
}
});}
public void startRecording() throws IOException
{
recording=true;
String path= Environment.getExternalStorageDirectory().toString();
File sampleDir = new File(path+"/DCIM/Squlium Booth");
sampleDir.mkdir();
Log.i("Setting Path", sampleDir.toString());
try {
audiofile = File.createTempFile("SqB", ".3gp", sampleDir);
} catch (IOException e) {
return;}
Log.i("Recording Activity", "Seting Media Recorder attributes");
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setMaxDuration(60000);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setOutputFile(audiofile.getAbsolutePath());
mrec.prepare();
mrec.start();
startProgress(myview);
}
protected void stopRecording() {
recording=false;
mrec.stop();
mrec.release();
mCamera.lock();
mCamera.release();
mrec2.stop();
mrec.release();
}
public void startProgress(View view) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
String path= Environment.getExternalStorageDirectory().toString();
File sampleDir = new File(path+"/DCIM/Squlium Booth");
sampleDir.mkdir();
try {
audiofile2 = File.createTempFile("myAudio", ".mp3", sampleDir);
} catch (IOException e) {
return;}
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat .CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
mrec2.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec2.setAudioSamplingRate(16000);
mrec2.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mrec2.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrec2.setOutputFile(audiofile2.getAbsolutePath());
try {
mrec2.prepare();
} catch (IllegalStateException e1) {
Log.i("Illegal", "Exception");
e1.printStackTrace();
} catch (IOException e1) {
Log.i("Iinput output", "Exception");
}
Log.i("Inside Run Method", "Starting Thread soon there will be issue");
mrec2.start();
Log.i("Inside Run Method", "After start method inside thread");
Log.i("Inside Thread", "Alive");
}
};
new Thread(runnable).start();
}

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!

Categories

Resources