views:

45

answers:

2

I have a simple, classic, statement that every 200 milliseconds plays a sound (a metronome).

I wrote it using Handlers, and then in another way, using Threads. The problem is the same in both ways: when I press hardware home button, or also simply when I press a button to open a ListView, the metronome terribly slowdown for a while.

This problem (not so strong, but however present) presents also doing nothing and leaving the application in foreground.

Any ideas?

Here's the code:

public class Metronome implements Runnable{

private Handler mHandler = new Handler();
public static long mStartTime;

Main mainContext; 

public Metronomo(Main context) {
    mainContext = context;
}


public void play() {
    mStartTime = System.currentTimeMillis();
    mHandler.postDelayed(this, 100);
}

public final void stop(){
    mHandler.removeCallbacks(this);
}

public void run(){
        //play the ogg file in position 1
        mSoundManager.playSound(1);

        //reschedule the next playing after 200ms
        mHandler.postAtTime(this, SystemClock.uptimeMillis() + 200);
   }

};

A: 

Hi. Are you using some kind of pause statement to wait between beats? You could try basing the timing on multiples of a system clock value instead. That way you may still get beats that occur late (or not at all) but you wouldn't get a slow down. Hope that makes some kind of sense.

This is more of a comment but I don't have enough rep to leave comments just yet.

learnvst
A: 

My phone seems to be able to play midi files, which are a pretty compact way to represent sound, perhaps you could dynamically create one and use that for the metronome? I'm assuming that the synthesis is handled at a lower level than would ordinarily be accessible to you so that the timing would be better, but I don't know that for a fact.

Chris Stratton
Similar idea: generate a sound stream that has the metronome sound followed by silence, rather than play the sound and stop. So long as your thread gets enough CPU time to keep the sound buffer full, your metronome will stay on time, even if other stuff in the system is active.
fadden