我正在制作适用于Android的应用程序,并且在它的核心中它有一个节拍器。 我需要在节拍中精确地发出声音。并且每第2个声音都被延迟了#34; swing"间隔百分比。 我目前的代码如下:
public void play() {
mainCountHandler.postDelayed(mainClick, 0);
subCountHandler.postDelayed(subClick, (MILLIS_IN_MINUTE/ (2 * bpm)) * (100 + swing));
}
private Runnable mainClick = new Runnable()
{
public void run()
{
playSound();
mainCountHandler.postDelayed(this, MILLIS_IN_MINUTE / bpm);
}
};
private Runnable subClick = new Runnable()
{
public void run()
{
playSound();
subCountHandler.postDelayed(this, MILLIS_IN_MINUTE / bpm);
}
};
private void playSound() {
final MediaPlayer mp = MediaPlayer.create(context, SOUND);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
++currentBeat;
if (currentBeat >= beatsCount) {
if (loop) {
currentBeat = 0;
} else {
stop();
}
}
}
这非常不准确。我尝试了 SoundPool ,并在 playSound 之外创建了 MediaPlayer ,并且没有任何重大变化。 那么有任何修改或者可能有其他可以帮助我的Android类吗?
答案 0 :(得分:2)
所以我能达到的最精确的节拍器看起来像这样:
public void play() {
mainTimer = new Timer();
subTimer = new Timer();
mainTimerTask = new MyTimerTask();
subTimerTask = new MyTimerTask();
mainTimer.schedule(mainTimerTask, 0, MILLIS_IN_MINUTE / bpm);
subTimer.schedule(subTimerTask, (300 * (100+swing)) / bpm, MILLIS_IN_MINUTE / bpm);
}
private void playSound() {
final MediaPlayer mp = MediaPlayer.create(context, SOUND);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
playSound();
}
}