Question

I'm writing an android application with Java in Eclipse.

The media player plays a track when a button is pressed, but I want this track to fade in and out randomly from total silence to full volume and anywhere in between.

I'm thinking of using a random number generator to determine output volume.

Any suggestions of how to do this and example code would be highly appreciated.

When I try this:

while (mp.isPlaying()) {
        float x = (float) Math.random();
        float y = (float) Math.random();
        setInterval((mp.setVolume(x,y)),2000);}

Eclipse tells me that setInterval is undefined. How do I fix this?

Was it helpful?

Solution

Use this function: it will give you a random int between min and max.

/** Returns a random int in the specified range. */
static int randomInt(float min, float max) {
    if (max < min) {
        max = min;
    }

    int randInt = (int) (new Random(System.nanoTime()).nextInt((int) (max - min + 1)) + min);
    return randInt;
}

You can create a simple loop using a Handler to fade the volume in and out as well:

void increaseVolume() {
    if (volume < 1) {
        volume += 0.01;

        new Handler().postDelayed(new Runnable {
        @Override
        public void run() {
                increaseVolume();
                mp.setVolume(volume);
            }
        }, 100);
    } else {
        volume = 1;
    }
}

Remember to also add float volume = 0 at the start of your activity to store the volume in between adjustments.

OTHER TIPS

To get random numbers , use :

volume = random.nextInt(maxvol - minvol) +minvol;

where maxvol corresponds to maximum volume and minvol corresponds to minimum volume.

Note: You can also use nextfloat() instead or with nextint() for extra precision.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top