sound waves during recording in android - 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.

Related

Record and Save Audio in One Activity and Play back Audio in Another Activity

In my App with many activities, I am trying to make a recording in one activity and store it in the phone files. Then in another activity, I want to play that file back. I think I may have a problem with with how I am saving the original file because it crashes on the second activity when it wants to read the file. I am not sure how to save in one activity and then read that audio file in the next activity. I have included what I thought was relevant code from both activities.
//This is the Activity that simply records and then saves the audio file
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context mContext = getApplicationContext();
createTempFile("Status_Recorder.txt", "INPROGRESS");
/*
* Create the file where the audio tone that is recorded will be saved
*
*/
try{
FileOutputStream fOut = openFileOutput("audio_test_right.3gp" , MODE_WORLD_READABLE);
}catch(IOException e) {
e.printStackTrace();
exit_function();
}
path = mContext.getFilesDir()+"/audio_test_right.3gp";
start_recording();
}
//Method to Start the Recording
private void start_recording() {
//Intialize the recorder
try{
speaker_recorder = new MediaRecorder();
speaker_recorder.reset();
} catch(Exception e){
Log.e(log_tag,"Recorder Initialization Failed");
createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
}
//Setting for the Recorder
try{
Log.i(log_tag,"Setting the recorder");
speaker_recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
speaker_recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
speaker_recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
speaker_recorder.setOutputFile(path);
} catch(Exception e){
Log.e(log_tag,"Recording Settings Failed");
createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
}
//Prepare the Recorder
try{
Log.i(log_tag,"Preparing the Recorder");
speaker_recorder.prepare();
} catch(Exception e){
Log.e(log_tag,"Recording failed");
createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
exit_function();
}
//Start the Recorder
try {
Log.i(log_tag,"Starting the recorder");
title_text = ((TextView) findViewById(R.id.textView));
title_text.setTextColor(Color.RED);
title_text.setText("RECORDING");
speaker_recorder.start();
// Thread.sleep(10000);
mHandler.postDelayed(new Runnable() {
public void run() {
createTempFile("Status_Recorder.txt", "COMPLETED-RECORDER FAILED");
exit_function();
}
}, timer);
} catch (Exception e) {
Log.e(log_tag,"Recorder start failed");
createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
exit_function();
}
}
private void exit_function() {
if (speaker_recorder != null) {
speaker_recorder.release();
}
onDestroy();
}
#Override
/*
* (non-Javadoc)
* #see android.app.Activity#onDestroy()
* Function invoked before we exit the application . Reset all the volume
* and stream values in this function
*/
protected void onDestroy() {
Log.i(log_tag,"Entered onDestroy()");
super.onDestroy();
this.finish();
}
/*
* Function to create the a text file in the application directory context. This function
* takes the file name and the string that is to be written in it as the input. This function is invoked
* to create the Result.txt file.
*/
private void createTempFile(String filename, String text) {
try {
FileOutputStream fOut = openFileOutput(filename , MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(text);
osw.flush();
osw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
//This is the Second Activity, but it Crashes when it gets to the mp.setDataSource(path); because I guess it cant find the path
private void playSound(boolean speakers) {
mContext = getApplicationContext();
// audioManager.setMicrophoneMute(true);
path = mContext.getFilesDir() + "/audio_test_right.3gp";
audioManager.setSpeakerphoneOn(true);
try {
mp.setDataSource(path);
} catch (IOException e) {
e.printStackTrace();
}
if (speakers) {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
} else {
mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
}
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
createTempFile("Status_RightSpeaker.txt", "COMPLETED");
exit_function();
}
});
}
}
Ok, so i have a working code for your question
This method when supplied with true will start recording else it will stop recording. So you can do this on your first activity
private void startOrStopRecording(boolean record){
if (record) {
// Record the audio
mMediaRecorder = new MediaRecorder();
mMediaRecorder.reset();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setOutputFile(getFilesDir().getAbsolutePath() + "/audio_test.3gp");
try {
mMediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mMediaRecorder.start();
}else{
// Stop recording
if (mMediaRecorder != null){
mMediaRecorder.stop();
mMediaRecorder.release();
mMediaRecorder = null;
}
}
}
This method when supplied with true starts to play the sound else stop. So you can implement it on your Second Activity
NOTE String mFile = getFilesDir().getAbsolutePath() + "/audio_test.3gp";
private void playOrStop(boolean play){
mPlayer = new MediaPlayer();
try{
if (play){
mPlayer.setDataSource(mFile);
mPlayer.prepare();
mPlayer.start();
}else {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}catch (IOException e){
Log.e("Mtali", e.getMessage());
}
}
Be sure to add the permission
<uses-permission android:name="android.permission.RECORD_AUDIO" />
B.O.N.U.S
You can use ToggleButton to
START & STOP RECORDING
JAVA
final ToggleButton recordButton = (ToggleButton) findViewById(R.id.record_button);
recordButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
startOrStopRecording(isChecked);
}
});
XML
<ToggleButton
android:id="#+id/record_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="#string/start_playback_string"
android:textOn="#string/stop_playback_string"/>
START AND STOP PLAYING
JAVA
ToggleButton button = (ToggleButton) findViewById(R.id.play_button);
button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
playOrStop(isChecked);
}
});
XML
<ToggleButton
android:id="#+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textOff="#string/start_playback_string"
android:textOn="#string/stop_playback_string"/>

Android Activity Will not Playback Recording

I am trying to make an recording in one activity and then play it back in another activity. I have no trouble doing this if it is in the same activity. When I split it, I can't seem to get it to work out at all. Everything is the same, just split, so I assume it cant find the path to the file saved on the phone. Please help!!!
This is the first activity where the recording takes place:
public class RecorderActivity2 extends Activity {
MediaRecorder recorder = null; //Recorder object used to record the audio tone
String path = null; //Stores the path of the media files that is been recorded
TextView title_text;
//How long the Recording lasts
int timer = 10000;
String log_tag = "Recorder1";
//DELAY AFTER THE RECORDING IS COMPLETED
int delay = 10000;
String file;
Context mContext;
Handler mHandler = new Handler();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* API's to launch the application when the tablet is locked or
* display is turned off
*/
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
setContentView(R.layout.activity_recorder);
//Check to see if the device has a microphone
PackageManager pm = getPackageManager();
boolean micPresent = pm.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
boolean playerPresent = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT);
if (!micPresent){
Log.i(log_tag, "There is no microphone present in this device.");
exit_function();
}
else {
createTempFile("Status_Recorder.txt", "INPROGRESS");
/*
* Create the file where the audio tone that is recorded will be saved
*
*/
path = getApplicationContext().getFilesDir().getAbsolutePath() + "/audio_test.3gp";
try {
FileOutputStream fOut = openFileOutput("audio_test.3gp", MODE_WORLD_READABLE);
} catch (IOException e) {
e.printStackTrace();
Log.e(log_tag, "FAILED TO CREATE THE FILE OUTPUT STREAM");
exit_function();
}
start_recording();
}
}
//Method to Start the Recording
private void start_recording() {
if (recorder != null) {
recorder.release();
}
//Setting for the Recorder
try{
Log.i(log_tag,"Setting the recorder");
// MediaRecorder.
recorder = new MediaRecorder();
recorder.reset();
//audioManager.setMicrophoneMute(false);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
} catch(Exception e){
Log.e(log_tag,"Recording Settings Failed");
createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
exit_function();
}
//Prepare the Recorder
try{
Log.i(log_tag,"Preparing the Recorder");
recorder.prepare();
} catch(Exception e){
Log.e(log_tag,"Recording failed");
createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
exit_function();
}
//Start the Recorder
try {
Log.i(log_tag,"Starting the recorder");
title_text = ((TextView) findViewById(R.id.textView));
title_text.setTextColor(Color.RED);
title_text.setText("RECORDING");
recorder.start();
//The recording lasts as long as he timer and then stops
mHandler.postDelayed(new Runnable() {
public void run() {
if (recorder != null) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
Log.e(log_tag,"First Delay");
exit_function();
}
}, 5000);
createTempFile("Status_Recorder.txt", "Complete");
//This Delay is between Recording and Playback
mHandler.postDelayed(new Runnable() {
public void run() {
}
}, 5000);
} catch (Exception e) {
Log.e(log_tag,"Recorder start failed");
createTempFile("Status.txt", "COMPLETED-RECORDER FAILED");
exit_function();
}
}
private void exit_function() {
onDestroy();
}
#Override
/*
* (non-Javadoc)
* #see android.app.Activity#onDestroy()
* Function invoked before we exit the application . Reset all the volume
* and stream values in this function
*/
protected void onDestroy() {
Log.i(log_tag,"Entered onDestroy()");
super.onDestroy();
if (recorder != null) {
recorder.release();
}
this.finish();
}
/*
* Function to create the a text file in the application directory context. This function
* takes the file name and the string that is to be written in it as the input. This function is invoked
* to create the Result.txt file.
*/
private void createTempFile(String filename, String text) {
try {
FileOutputStream fOut = openFileOutput(filename , MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(text);
osw.flush();
osw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
This is from the Second Recording that plays back the recording:
public class RecorderPlaybackActivity extends Activity {
int default_mode; //Saves the default mode of the device
int music_volume; //Saves the default volume of the music stream
int call_volume; //Saves the default volume of the in call stream
AudioManager audioManager = null; //Object to provide access to system volume controls and settings
MediaPlayer mPlayer = null; //Media object which has the playback control of audio and video files
String path = null; //Stores the path of the media files that is been recorded
TextView title_text;
//How long the Recording lasts
int timer = 10000;
String log_tag = "RecorderPlayback";
//DELAY AFTER THE RECORDING IS COMPLETED
String file;
final static int FOR_MEDIA = 1;
final static int FORCE_NONE = 0;
final static int FORCE_SPEAKER = 1;
Class audioSystemClass = null;
Method setForceUse = null;
int volume = 20;
Context mContext;
Handler mHandler = new Handler();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* API's to launch the application when the tablet is locked or
* display is turned off
*/
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
setContentView(R.layout.activity_recorder);
//Check to see if the device supports audio output
PackageManager pm = getPackageManager();
boolean playerPresent = pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT);
if (!playerPresent){
Log.i(log_tag, "There is no audio player present in this device.");
exit_function();
}
else {
createTempFile("Status_Recorder.txt", "INPROGRESS");
/*
* Create the file where the audio tone that is recorded will be saved
*
*/
try {
FileOutputStream fOut = openFileOutput("audio_test.3gp", MODE_WORLD_READABLE);
} catch (IOException e) {
e.printStackTrace();
Log.e(log_tag, "FAILED TO CREATE THE FILE OUTPUT STREAM");
exit_function();
}
path = getApplicationContext().getFilesDir().getAbsolutePath() + "/audio_test.3gp";
audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
default_mode = audioManager.getMode();
music_volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
call_volume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
// //Setting the volume level
// audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
// audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,volume, AudioManager.FLAG_SHOW_UI);
//Setting the volume to max
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
try {
audioSystemClass = Class.forName("android.media.AudioSystem");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
start_playback();
}
}
public void start_playback() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
mPlayer = new MediaPlayer();
//Setting the playback path
try {
Log.i(log_tag, "setting the data source");
mPlayer.setDataSource(path); //The variable path contains the file path where the recorded tone was saved
} catch (Exception e) {
Log.e(log_tag, "exception while setting the data source");
createTempFile("Status.txt", "COMPLETED-PLAYER FAILED");
exit_function();
}
//Preparing the playback
try {
mPlayer.prepare();
} catch (Exception e) {
Log.e(log_tag, "prepare() failed");
createTempFile("Status.txt", "COMPLETED-PLAYER FAILED");
exit_function();
}
//Playing the recording
try {
Log.i(log_tag, "starting the audio playback # " + (count+1));
title_text.setText("PLAYING RECORDING #" + (count+1));
audioManager.setSpeakerphoneOn(true);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mPlayer) {
//Change this delay for break in between playback
mHandler.postDelayed(new Runnable() {
public void run() {
if (count <1){
count++;
start_playback();
}
else{
createTempFile("Status_Recorder.txt", "COMPLETED");
exit_function();
}
}
}, 0);
}
});
} catch (Exception e) {
Log.e(log_tag, "start failed");
createTempFile("Status.txt", "COMPLETED-PLAYER FAILED");
exit_function();
}
}
private void exit_function() {
onDestroy();
}
#Override
/*
* (non-Javadoc)
* #see android.app.Activity#onDestroy()
* Function invoked before we exit the application . Reset all the volume
* and stream values in this function
*/
protected void onDestroy() {
Log.i(log_tag,"Entered onDestroy()");
super.onDestroy();
if (mPlayer != null) {
mPlayer.release();
}
//Reset to the default settings here
audioManager.setMode(default_mode);
try {
setForceUse.invoke(null, FOR_MEDIA, FORCE_NONE);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, music_volume, 0);
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, call_volume, 0);
this.finish();
}
/*
* Function to create the a text file in the application directory context. This function
* takes the file name and the string that is to be written in it as the input. This function is invoked
* to create the Result.txt file.
*/
private void createTempFile(String filename, String text) {
try {
FileOutputStream fOut = openFileOutput(filename , MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(text);
osw.flush();
osw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
I was able to finally figure out what I was doing wrong. I had the following line at the top of both activities:
//Create the file that will be used to save the recording
try {
FileOutputStream fOut = openFileOutput("audio_test.3gp", MODE_WORLD_READABLE);
} catch (IOException e) {
e.printStackTrace();
Log.e(log_tag, "FAILED TO CREATE THE FILE OUTPUT STREAM");
exit_function();
}

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

Media recorder in android

Hello i have create a small application in which i am recording audio. My problem is, in following code i can create a file in specific folder but when i am trying to play this audio file it says this media file is not supporting. plz help
public void startRecording() {
System.out.println("STart Recording");
if (recorder != null) {
recorder.release();
} else {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(getFilePath());
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
recorder.release();
}
}
}
private void stopRecording() {
System.out.println("Stop Recording");
try {
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
private String getFilePath() {
File rsd = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
if (!rsd.isDirectory()) {
rsd.mkdir();
}
File dcim = new File(rsd + "/hello.mp3");
return dcim.getAbsolutePath();
}
Yup like Ralph House said in comment, you should save your file with .3gp extention. Change
File dcim = new File(rsd + "/hello.mp3");
To:
File dcim = new File(rsd + "/hello.3gp");

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