我有一个自定义视图(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
。所以,假设你能让它与安卓MediaPlayer
一起工作,我可以接受。
特别感谢Mike M先生的宝贵意见。我能够使用MediaPlayer
修复它。应该调用MediaPlayer.release()
方法。为了使声音与角运动同步,我保留了一个if块,用于检查旋转dTheta
是否大于tolerance
角度。因此,如果有人需要它,完整的代码看起来是这样的:
public PieView extends View{
private float omega0; // holds the previous rotation
/**
* @brief: plays a music using mediaPlayer
* @input:
* @output: void, plays a music
* */
private void myPlayTick() {
float omega1 = Math.abs(getRotation());
float dOmeda = 0;
if(omega1>omega0){
dOmeda = omega1 - omega0;
}else{
dOmeda = omega0-omega1;
}
if(dOmeda > threshold){
omega0 = omega1; // update previous rotation
final MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.magicbox_tick);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer(mp);
}
});
}
}
/**
* @brief: releases mediaPlayer resource so that other mediaPlayers can use sound hardware resources
* @input: MediaPlayer object
* @output: void
* */
private void releaseMediaPlayer(MediaPlayer mediaPlayer) {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void rotateTo(){
animate()..setInterpolator(new DecelerateInterpolator())
.setDuration(mDuration)
.setListener(someListener)
.rotation(targetAngle)
.setUpdateListener(animation -> {
myPlayTick();
})
.start();
}
// ... rest of the code, such as constructors, etc
}