Media Recorder record application audio - android

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.

Related

how to stop Mediaplayer

I am having 3 tones. I am calling playmusic() function to play 2 of these tones on imageview toggle. when i click on imageview for first time tone1 starts playing. when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
my requiremet is , when i click on imageview for -
(1st time - tone1 should start playing).
(2nd time - tone1 should stop playing and tone2 should start playing)
(3rd time - tone2 should stop playing and tone1 should start playing again)
and so on....
String file=null;
int x=0;
public void playMusic(int i) {
x=i;
if(i==1){
file = R.raw.tone1;
}else if(i==2){
file = R.raw.tone2;
}else{
file = R.raw.tone3;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
Main2Activity.this.getResources().openRawResourceFd(file);
if(assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
I did a small modification on your logic and added mediaplayer.reset(). Here is the solution link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView player = findViewById(R.id.play);
player.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
playMusic(1);
}
});
mediaPlayer = new MediaPlayer();
}
int file = 0;
MediaPlayer mediaPlayer;
int x = 0;
public void playMusic(int i) {
x = x + i;
if (x == 1) {
file = R.raw.tone1;
}
else if (x == 2) {
file = R.raw.tone2;
} else {
x = 0;
file = R.raw.tone3;
}
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
MainActivity.this.getResources().openRawResourceFd(file);
if (assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
}
when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
If that's the only issue, try putting the following line before you call mediaPlayer = new MediaPlayer();:
if (mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();

Do something when playing ends

I have a button that starts playing a recorded audio when pressed. Also it's icon changes. I want to change the icon again when the playing ends. Can somebody give me an example or something? Thank you :)
Here is my audio class:
public class Audio {
private MediaPlayer mPlayer;
private MediaRecorder mRecorder;
public String path;
public void setPath(String path) {
this.path = path;
}
public void stopPlayRecorded() {
if (mPlayer != null) {
mPlayer.stop();
}
}
public void playRecorded() throws IllegalArgumentException,
SecurityException, IllegalStateException, IOException {
ditchMediaPlayer();
File f = new File(path);
if(!recordingExists(f)) {
return;
}
mPlayer = new MediaPlayer();
mPlayer.setDataSource(path);
mPlayer.prepare();
mPlayer.start();
}
private void ditchMediaPlayer() {
if (mPlayer != null) {
try {
mPlayer.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
ditchMediaRecorder();
}
}
public void beginRecording() throws IllegalStateException, IOException {
File f = new File(path.substring(0, path.lastIndexOf("/")));
if (!recordingExists(f)) {
f.mkdirs();
}
ditchMediaRecorder();
File outFile = new File(path);
Log.d("R_PATH", path);
if (outFile.exists()) {
outFile.delete();
}
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(path);
mRecorder.prepare();
mRecorder.start();
}
public boolean recordingExists(File f) {
if (f.exists())
return true;
else
return false;
}
private void ditchMediaRecorder() {
if (mRecorder != null) {
mRecorder.release();
}
}
}
Yes you can do that with OnCompletionListener:
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do something when the end of a media source
// has been reached during playback.
}
});

How do I release MediaPlayer after it finishes playing a sound?

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

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!

Surface view getting problem

i am new to android, currently doing dynamic multimedia application. For accessing videos, included tappable SurfaceView. whenever playing videos from localhost server, only sound's can visible, there is no visual. i am not sure why this will happen, can anyone guide me how to visualize the video.
if (player == null) {
player = new MediaPlayer();
player.setScreenOnWhilePlaying(true);
} else {
player.stop();
player.reset();
}
player.setDataSource(file);
player.setDisplay(holder);
player.prepareAsync();
//player.setOnBufferingUpdateListener(this);
player.setOnCompletionListener(this);
player.setOnPreparedListener(this);
player.setOnVideoSizeChangedListener(this);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Here setDataSoruce (file) is used to get localhost url from existing class using intent.
Check out my Surface View - Playing video tutorial
public class VideoAssetActivity extends Activity implements
TextureView.SurfaceTextureListener {
// Log tag.
private static final String TAG = VideoAssetActivity.class.getName();
// Asset video file name.
private static final String FILE_NAME = "big_buck_bunny.mp4";
// MediaPlayer instance to control playback of video file.
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.texture_video_simple);
initView();
}
private void initView() {
TextureView textureView = (TextureView) findViewById(R.id.textureView);
textureView.setSurfaceTextureListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i2) {
Surface surface = new Surface(surfaceTexture);
try {
AssetFileDescriptor afd = getAssets().openFd(FILE_NAME);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mMediaPlayer.setSurface(surface);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepareAsync();
// Play video when the media source is ready for playback.
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
} catch (IllegalArgumentException e) {
Log.d(TAG, e.getMessage());
} catch (SecurityException e) {
Log.d(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.d(TAG, e.getMessage());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i2) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
}

Categories

Resources