【发布时间】:2020-04-06 03:30:21
【问题描述】:
我有一个自定义视图 (PieView),它有一个旋转动画。现在我想用旋转速度同步播放tick tick tick tick...声音(即旋转速度快时滴答滴答应该快,旋转慢时滴答滴答应该慢)。
为此,首先我创建了一个名为 magicbox_tick.mp3 的 mp3 文件,该文件只有一 (1) 个刻度。接下来我尝试用Animation.setUpdateListener()播放声音。
首先,我尝试使用MediaPlayer 播放音乐,但在大约 10 或 15 个滴答声之后,它停止了。所以现在我正在尝试SoundPool 播放音乐。
相关代码段如下所示:
public PieView extends View {
// ... constructors, other methods etc
private SoundPool soundPool;
private int soundId;
void init(){ // called inside those constructors
SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
soundId = soundPool.load(getContext(), R.raw.magicbox_tick, 1);
}
public void rotateTo(){
animate()..setInterpolator(new DecelerateInterpolator())
.setDuration(mDuration)
.setListener(someListener)
.rotation(targetAngle)
.setUpdateListener(animation -> {
myPlaySound(); // <----------------------- This is the sound playing code
})
.start();
}
void myPlaySound(){
soundPool.play(soundId, 1, 1, 0, 0, 1); // this doesnot play the `tick` sound
// previously I used MediaPlayer like this:
/*
MediaPlayer mp = new MediaPlayer.create(getContext(), R.raw.magicbox_tick);
mp.play();
// these 2 line, after some 10 ticks, stopped working.
*/
}
}
我从来没有做过这样的事情,我不知道如何解决这个问题。谁能帮我?
请注意,只要可行,我对所有答案持开放态度。您不必使用SoundPool。因此,假设您可以使其与 android MediaPlayer 一起使用,我可以接受。
【问题讨论】:
-
MediaPlayer方法可能会停止工作,因为您每次都在创建一个新的MediaPlayer实例,并且永远不会释放它们:stackoverflow.com/a/35097745。您是否尝试过使用一开始就创建的单个实例,然后每次都重放它? -
我确实尝试过使用单个实例,但
ticks 听起来不太正确。所以我尝试创建新实例。但我没有释放它们。让我尝试发布 MediaPlayer。 -
看起来它正在工作。谢谢! :D
标签: java android android-animation android-mediaplayer soundpool