Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";

    }

}
like image 640
code511788465541441 Avatar asked Mar 03 '13 18:03

code511788465541441


1 Answers

Try this

 voicePlayer.getMediaPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.stop();
            if (mediaPlayer != null) {
                mediaPlayer.killMediaPlayer();
            }

        }
    });
like image 59
Gaurav Agarwal Avatar answered Nov 11 '22 10:11

Gaurav Agarwal