Search code examples
androideventsaudioandroid-mediaplayer

Trigger an event when mediaPlayer stops


I am making an app that uses sound effects. I would like to know how i can detect when a sound has finished playing and trigger an event .

i tried this :

 player = new MediaPlayer();
    if (player != null) {
        player.reset();
        player.release();
    }

    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {

            sonar.setBackgroundResource(R.drawable.sonar_off);
            stopPlay();
        }
    });

        if(state==1){
            player = MediaPlayer.create(this, R.raw.sonar_slow);
        }else if(state==2){
            player = MediaPlayer.create(this, R.raw.sonar_medium);
        }else if(state==3){
            player = MediaPlayer.create(this, R.raw.sonar_fast);
        }
         try{
             player.prepare();
            } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            } 
        player.start();

Solution

  • You can set an OnCompleteListener() to the player object. The code for it is:

    mPlayer.setOnCompletionListener(new OnCompletionListener() {
         @Override
         public void onCompletion(MediaPlayer mp) 
                 { 
                    "your code comes here" 
                 }
    });
    

    Here the mPlayer is the object of the MediaPlayer which is currently running.