Stack Overflow archive
1 score

Play sound every 6-10 seconds

score
1
question views
2.2K
license
CC BY-SA 3.0

You can get a random number between 6 and 10 like this:

java
int max = 10;
int min = 6;
int randomNum = new Random().nextInt((max - min) + 1) + min;
int seconds = randomNum * 1000;

Here is an example to play a sound every 6 to 10 seconds:

java
private final Random mRandom = new Random();

private final Handler mHandler = new Handler();

private MediaPlayer mPlayer;

private boolean mKeepPlaying = true;

private void playMySound() {
    if (mPlayer == null) {
        mPlayer = MediaPlayer.create(this, R.raw.whistle);
    }
    int delayMillis = 1000 * mRandom.nextInt(5) + 6; // random number between 6 and 10
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (isFinishing()) {
                // Check if the Activity is finishing.
                return;
            }
            mPlayer.start();
            if (mKeepPlaying) {
                // play the sound again in 6 to 10 seconds
                playMySound();
            }
        }
    }, delayMillis);
}

Just call playMySound(); in onCreate(Bundle) and toggle mKeepPlaying when you want to stop.

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.