MartijnG MartijnG - 19 days ago 6
Android Question

Android Loop beat with a Handler

What I'm trying to understand is how to loop a simple beat in a given time frame using a

Handler
like a metronome. I've read a lot and saw a few things I can do but the best way is make a
Handler
, is this true? So after reading I tried something but I can't understand it exactly and it's not working right now.

EDIT:

This is what I have now, it's not crashing anymore but it isn't playing the sound like it should. What did I do wrong?

public class MainActivity extends Activity {

private MediaPlayer mpBeat;

private Handler playBeatHandler = new Handler();
private Runnable playBeatTask = new Runnable() {
public void run() {
mpBeat.start();
playBeatHandler.postDelayed(this, 500);
}
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mpBeat = MediaPlayer.create(this, R.raw.beat);
playBeatHandler.postDelayed(playBeatTask, 500);
}
}

Answer

This is what I came across and what helped me a lot to build a steady beat!

http://code.google.com/p/android-sleep-metronome/