Broak
Broak

Reputation: 4187

Get random sound file from raw folder - Android - MediaPlayer

I'd like to:

  1. Generate a random number (easy enough)
  2. take that random number and add it to some sort of dynamic path
  3. use the dynamic path in the mediaplayer creation.

E.g.

Resource folder(raw) contains 1.mp3 2.mp3 3.mp3

Random number generates a number between 0 and 4

e.g: 2

Inserts random number to path

E.g. a String?

String PATH = "R.raw." + RANDOM-NUMBER

MediaPlayer mp = MediaPlayer.create(context, PATH);

However, of course MediaPlayer uses a URI variable not a string, i did try

myUri = Uri.parse("R.raw.2"); 

but get a nullPointerException

I imagine this is very simple/straight forward to answer and my knowledge simply evades me

Thanks very much

Upvotes: 0

Views: 4372

Answers (2)

Karel Bruyneel
Karel Bruyneel

Reputation: 21

Personally I would do it like this:

    //initializing the sounds
    final MediaPlayer sound1 = MediaPlayer.create(this, R.raw.1);
    final MediaPlayer sound2 = MediaPlayer.create(this, R.raw.2);
    final MediaPlayer sound3 = MediaPlayer.create(this, R.raw.3);

    //generate random number
    Random randomGenerator = new Random();
    int randomInt = randomGenerator.nextInt(3) + 1;

    //picking the right sound to play
    switch (randomInt){
    case 1: sound1.start();
    break;
    case 2: sound2.start();
    break;
    case 3: sound3.start();
    break;
    }

Upvotes: 2

Zaid Daghestani
Zaid Daghestani

Reputation: 8615

You cant do that with resources. Here's how I see you'd go about it.

int randomInt = generateRandomInt(), id;
switch (randomInt) {
case 1:
    id = R.raw.1;
    break;
case 2:
    id = R.raw.2;
    break;
...
}
setDataFromResource(getResources(), myMediaPlayer, id);

AFAIK, you have to use setDataFromResource to set the data for your media player from R.raw

Upvotes: 4

Related Questions