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();
}
Related
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());
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"/>
I have an application that has a few buttons that have sounds (soundPool) I need to write them down on a flash card I make it through the MediaRecorder but when I run the app and then turn on the record playing and click stop recording application crashes you do not tell me what the problem is?
I expect that in the method recordStop
public class MainActivity extends Activity {
int kickSound;
SoundPool mSoundPool;
AssetManager assets;
private MediaRecorder mediaRecorder;
private MediaPlayer mediaPlayer;
private String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
assets = getAssets();
kickSound = loadSound("snare_trap.ogg");
ImageButton kick = (ImageButton)this.findViewById(R.id.imageButton1);
kick.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
playSound(kickSound);
}
return false;
}
});
fileName = Environment.getExternalStorageDirectory() + "/record.3gpp";
}
protected void playSound(int sound) {
if (sound > 0)
mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
private int loadSound(String fileName) {
AssetFileDescriptor afd = null;
try {
afd = assets.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Couldn't load file '" + fileName + "'", Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
}
public void recordStart(View v) {
try {
releaseRecorder();
File outFile = new File(fileName);
if (outFile.exists()) {
outFile.delete();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(AudioManager.STREAM_MUSIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(fileName);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void recordStop(View v) {
mediaRecorder.stop();
}
public void playStart(View v) {
try {
releasePlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileName);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void playStop(View v) {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
}
private void releaseRecorder() {
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
}
}
private void releasePlayer() {
mediaPlayer.release();
mediaPlayer = null;
}
#Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
releaseRecorder();
}
}
Why are you releasing the recorder to start out with? Releasing should only be used if you don't want to access the recorder anymore. Try moving the release to the end.
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 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.