In Android 如何在AnimationSet中添加音效

In Android How to add a sound effect in an AnimationSet

我已经创建了一个 AnimationSet 并且想要在第一个动画之后有一个音效。是否可以通过某种方式将它添加到动画集​​中,或者如果有一个 ObjectAnimator 属性 可以改变 sound.Please 让我知道我该怎么做。

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

一种可能是向您的 ObjectAnimator 添加一个侦听器。例如:

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

这些方法将在每个阶段触发。您需要将 MediaPlayer 变量设为 final 变量,除非它具有更高的范围。

如果您的音频剪辑很短,那么 SoundPool 可能更适合这项工作,特别是当我们想要触发多个剪辑时。然而,在决定之前,您可能需要检查一下:AudioTrack, SoundPool or MediaPlayer Which Should I use?