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!
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());
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.
I have a soundboard like app. I don't want the sound to stop even if the user clicks another sound. But, after a while, like 30 clicks (sound players), it stops. I think it runs out of memory or Android is not letting it make more than 30 instances.
How can I implement this better so that when a sound has finished, the media player instance is destroyed?
import java.io.IOException;
public class AudioRecordTest {
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
public void startPlaying(int fileName) {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName + fileName + ".3gp");
mPlayer.prepare();
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopPlaying() {
try {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public MediaPlayer getPlayer() {
return mPlayer;
}
public void startRecording(int fileName) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName + fileName + ".3gp");
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
e.printStackTrace();
}
try {
mRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopRecording() {
try {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public AudioRecordTest() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/aaa";
}
}
Try this
voicePlayer.getMediaPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
if (mediaPlayer != null) {
mediaPlayer.killMediaPlayer();
}
}
});
Try this:
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
Or:
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.release();
mediaPlayer = null;
}
});
You can use release() of medeiaplayer
if(!mediaPlayerObject.isPlaying())
mediaPlayerObject.release();
EDIT: When I click the record button a second time ( to stop recording ) it force closes the app. The specific code for that event:
else if(isrec) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
isrec = false;
Toast.makeText( getApplicationContext(),"No longer recording!",Toast.LENGTH_SHORT).show();
}
(Original question):
I'm having trouble trying to get an app to record sound on a button click. I've included the code... and here's what my Toasts tell me:
after setAudioSource
after setOutputFile
isrec is not true
trying...
caught IO Exception...
Any help is greatly appreciated.
private OnClickListener micListener = new OnClickListener() {
boolean isrec = false;
public void onClick(View v) {
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
Toast.makeText( getApplicationContext(),"after setAudioSource",Toast.LENGTH_SHORT).show();
recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
File outputFile = null;
outputFile = getFileStreamPath("output.amr");
recorder.setOutputFile(outputFile.getAbsolutePath());
Toast.makeText( getApplicationContext(),"after setOutputFile",Toast.LENGTH_SHORT).show();
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
if(!isrec) {
Toast.makeText( getApplicationContext(),"isrec is not true",Toast.LENGTH_SHORT).show();
try {
Toast.makeText( getApplicationContext(),"trying...",Toast.LENGTH_SHORT).show();
recorder.prepare();
recorder.start();
isrec = true;
Toast.makeText( getApplicationContext(),"Recording!",Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText( getApplicationContext(),"caught IllegalState Exception...",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText( getApplicationContext(),"caught IO Exception...",Toast.LENGTH_SHORT).show();
}
} else if(isrec) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
isrec = false;
Toast.makeText( getApplicationContext(),"No longer recording!",Toast.LENGTH_SHORT).show();
}
}
};
First of all, you should use a boolean for isrec instead of a string
That :
FileDescriptor fileName = null;
recorder.setOutputFile(fileName);
That means you want to record on a file which is null
If you create a file, and you pass it as a parameter of your recorder, it should work.
Edit : Sometimes the release doesn't work when you want to stop the recorder.
So, just keep stop() and reset()
Try the following code for the main activity :
public class AudioRecordTestActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public AudioRecordTestActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
and in the manifest file specify the following permissions
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Maybe this will help? The article will show you how to solve two issues:
Show the way to record WAV file.
Record audio with best quality as possible.
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.