Cannot Record twice Android - android

I am making an app where i can record something and then play it back but when i try to record again my APP crashes.
In the logs I get
01-18 16:51:39.368 27426-27426/com.example.se414011.musicapp1
W/MediaRecorder﹕ mediarecorder went away with unhandled events 01-18
16:51:42.598 27426-27426/com.example.se414011.musicapp1 A/libc﹕ Fatal
signal 11 (SIGSEGV) at 0x00000010 (code=1), thread 27426
(14011.musicapp1)
Any help would be great thanks!
This is my code
public void start(View view) {
try {
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 Status: Recording");
stopBtn.setEnabled(true);
startBtn.setEnabled(false);
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
public void stop(View view) {
try {
myRecorder.stop();
myRecorder.release();
text.setText("Recording Status: Stop recording");
stopBtn.setEnabled(false);
startBtn.setEnabled(true);
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();
text.setText("Recording Status: 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);
startBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Status: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

As you can see in documentation, you can reuse your MediaRecorder only if you don't release it, snippet:
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(PATH_NAME);
recorder.prepare();
recorder.start(); // Recording is now started
...
recorder.stop();
recorder.reset(); // You can reuse the object by going back to setAudioSource() step
recorder.release(); // Now the object cannot be reused
You didn't post where you set your object myRecorder, and if you create a new one when you want to record again, but if you're reusing the same object after calling release() you'll be in problems, my suggestions are don't release it until you're finished or create a new MediaRecorder for each record.
boolean stopped = false;
public void start(View view) {
//your code...
stopped = false;
}
public void stop(View view) {
try {
myRecorder.stop();
//myRecorder.release();
stopped = true;
//your code
}
}
public void onDestroy(){
if(stopped)
myRecorder.release();
}

Related

click stop button to stop the moving seekbar and show seekbar to start position while playing audio

I need to stop the moving seekbar on click the start button.And seekbar have to show in start position.
For that I tried, seekBar.setProgress(0) . But it is not working for me.Below I have posted the relevant code:
public void stopPlay(View view) {
try {
if(myPlayer.isPlaying()){
myPlayer.pause();
}
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Point: Stop playing");
seekBar.setProgress(0);
Toast.makeText(getApplicationContext(),
"Stop playing the recording...", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try like this
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
seekBar.setProgress(0);
}
});
} catch (Exception e) {
e.printStackTrace();
}

MediaRecorder do not start with code -38

I am trying to write video to socket (with ParcelFileDescriptor). But when calling mediaPlayer.start() method - an IllegalStateException occurs with this message - "E/MediaRecorder: start failed: -38".
Code for file descriptor (Socket is 100% properly connected by the time programm calls it):
public ParcelFileDescriptor getFileDescriptorToSocket() {
return ParcelFileDescriptor.fromSocket(socket);
}
Preparing media recorder:
private boolean prepareMediaRecorder() {
mediaRecorder = new MediaRecorder();
camera.unlock();
mediaRecorder.setCamera(camera);
// mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setPreviewDisplay(cameraSurface.getHolder().getSurface());
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setVideoSize(320, 240);
mediaRecorder.setVideoFrameRate(30);
//mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
mediaRecorder.setOutputFile(MainActivity.socketClient.getFileDescriptorToSocket().getFileDescriptor());
try {
mediaRecorder.prepare();
} catch (IllegalStateException ise) {
// TODO Delete test code
Log.d(TAG, "Error during MediaRecorder preparing: " + ise.getMessage());
ise.printStackTrace();
releaseMediaRecorder();
return false;
} catch (IOException ioe) {
// TODO Delete test code
Log.d(TAG, "Error during MediaRecorder preparing: " + ioe.getMessage());
ioe.printStackTrace();
releaseMediaRecorder();
return false;
}
return true;
}
and call for start recording:
private void startRecording() {
if (!prepareMediaRecorder()) {
// TODO Delete test code
Log.d(TAG, "Error starting recording process");
finish();
} else {
new Thread(new Runnable() {
#Override
public void run() {
try {
mediaRecorder.start();
} catch (Exception e) {
// TODO Delete test code
Log.d(TAG, "Error in recording thread: " + e.getMessage());
e.printStackTrace();
}
}
}).start();
recordingStatus = true;
}
}
I should note that when i disable start recording method - camera works fine - i can properly see camera preview surface.

Adding delay while Mediaplayer loops

Playing .wav file using MediaPlayer class. As I need to loop the Audio I've set .setLooping(true); . So obviously, the doubt is how do I add a delay each time the audio plays, say I want a delay of 5000 .
The answers to similar questions here doesn't work in my case. Any help would be appreciated. Here is my code:
Button Sample = (Button)findViewById(R.id.samplex);
Sample.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filePath = Environment.getExternalStorageDirectory()+"/myAppCache/wakeUp.wav";
try {
mp.setDataSource(filePath);
mp.prepare();
mp.setLooping(true);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
You need to register 2 listeners (on completion and on error) and then you would need to delay next play in on completion callback. Reason for the error listener is to return true to avoid calling on completion event whenever there is an error - explanation here
private final Runnable loopingRunnable = new Runnable() {
#Override
public void run() {
if (mp != null) {
if (mp.isPlaying() {
mp.stop();
}
mp.start();
}
}
}
mp.setDataSource(filePath);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
button.postDelayed(loopingRunnable, 5000);
}
});
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
...
return true;
});
mp.prepare();
// no need to loop it since on completion event takes care of this
// mp.setLooping(true);
Whenever your destruction method is (Activity.onDestroyed(), Fragment.onDestroy(), View.onDetachedFromWindow()), ensure you are removing the runnable callbacks, e.g.
#Override
protected void onDestroy() {
super.onDestroy();
...
button.removeCallbacks(loopingRunnable);
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
}

How to Play the online streaming radio in Android

I am developing one application where i want to play live stream radio. I have an url using which i will stream the radio and play. I have a play button by clicking which i want to play the radio. For that, i have written some code which is not at all working. Here is my code:
mp = new MediaPlayer();
try {
mp.setOnPreparedListener(this);
Log.d("Testing", "start111");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
String url="xxxxxx";
mp.setDataSource(url);
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.d("Testing", "Exception ::: 1111 "+e.getMessage());
} catch (IllegalStateException e) {
Log.d("Testing", "Exception ::: 2222 "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d("Testing", "IOException ::: 3333 "+e.getMessage());
e.printStackTrace();
}
Can anyone please help me??
You can find good information regarding radio streaming.
Github radio streaming example
and also there is a question in SOF which can also be helpful
Stackoverflow radio streaming example
Hope it will help. thanks
Try this.
public class RadioStream extends Activity {
private final static String stream = "http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p";
Button play;
MediaPlayer mediaPlayer;
boolean started = false;
boolean prepared = false;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_stream);
play = (Button) findViewById(R.id.play);
play.setEnabled(false);
play.setText("Loading..");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started) {
mediaPlayer.pause();
started = false;
play.setText("Play");
} else {
mediaPlayer.start();
started = true;
play.setText("Pause");
}
}
});
new PlayTask().execute(stream);
}
#Override
protected void onPause() {
super.onPause();
/* if(started)
mediaPlayer.pause();*/
}
#Override
protected void onResume() {
super.onResume();
/*if(started)
mediaPlayer.start();*/
}
#Override
protected void onDestroy() {
super.onDestroy();
// mediaPlayer.release();
}
private class PlayTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
play.setEnabled(true);
play.setText("Play");
}
}
}
Please do try the code below and call the given method at the on create of your activity or at the onclick listener of your button. Remember to handle the stop and start button the imgV is an imageView for my button.
private MediaPlayer player;
private void startMediaPlayer() {
String url = "http:yoururl.com"; // your URL here
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(isPlaying){
try {
mediaPlayer.prepareAsync();
progress.setVisibility(View.VISIBLE);
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
}
boolean isPlaying = true;
private void startPlaying() {
isPlaying = true;
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
imgV.setImageResource(R.drawable.stop);
}
private void stopPlaying() {
if (mediaPlayer.isPlaying()) {
isPlaying = false;
mediaPlayer.stop();
mediaPlayer.release();
initializeMediaPlayer();
}
imgV.setImageResource(R.drawable.play);
}

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