Search code examples
androidandroid-intentandroid-mediaplayerandroid-mediarecorder

Android stops mediaplayer audio


I have a "click" that is high frequency, but after 20-25 clicks the sound disappear..

 MediaPlayer mp;

                mp = MediaPlayer.create(mService.getApplicationContext(),R.raw.click2);
                mp.start();
            }

ANdroid blocks by Default this kind of loops?


Solution

  • Well I don't see a loop in the code you've provided, but if you actually are creating MediaPlayers in a loop and not calling release(), then you are going to cause errors by using up too much of the available resources. I have several tips for you.

    Tip #1: Don't use mService.getApplicationContext(), since (I assume) mService is a Service and already is a Context (Service inherits from Context). You should basically never use getApplicationContext().

    Tip #2: Use one MediaPlayer and pay attention to the state machine. Try something like this:

    MediaPlayer mp = new MediaPlayer();
    ...
    while (whateverCondition) { // I don't know what loop construct you are using...
        mp.reset();
        mp.setDataSource(this,
            Uri.parse("android.resource://com.your.package/" + R.raw.click2);
        mp.prepare();
        mp.start();
    }
    ...
    mp.release();
    

    You will need to fill in the package name as appropriate, but it should get you on the right track.