Search code examples
androidsoundpoolobjectanimator

In Android How to add a sound effect in an AnimationSet


I have created an AnimationSet and want a sound effect after the first animation. Is it possible to add it to the animation set in some way or if there is an ObjectAnimator property that changes sound.Please let me know how I can do that.

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.combo);
ObjectAnimator fade = ObjectAnimator.ofFloat(ImageButton,"alpha",0f,1f);
ObjectAnimator move = ObjectAnimator.ofFloat(myAnimation1,"translationX",20);
ObjectAnimator moveX = ObjectAnimator.ofFloat(myAnimation1,"translationY",20);
AnimatorSet as =new AnimatorSet();
                as.playTogether(move,moveY,fade);//wanted to know if I could add the sound  mp after moveY
                as.start();

Solution

  • One possibility is to add a listener to your ObjectAnimator. For example:

     mAnimator.addListener(new AnimatorListenerAdapter(){
          @Override public void onAnimationStart(Animator animator){
            // do something if needed when animation starts, play a sound maybe
          }
          @Override public void onAnimationEnd(Animator animator){
            // call your sound player from here
          }
        }
    );
    

    The methods will be triggered during each of the phases. You will need to make your MediaPlayer variable a final variable unless it has a higher scope.

    If your audio clip is a short one then perhaps a SoundPool would be better suited for the job specially when we want multiple clips to fire. However before deciding on that you may want to check this: AudioTrack, SoundPool or MediaPlayer Which Should I use?