0

Good day, I have a small app, it has one button. Whenever I press the button it makes sound using the MediaPlayer. The issue is that I can't find how to make same mediaplayer to play other sounds,

For example: I have list of 10 sounds, whenever I click on my button it randomly picks number from 1 to 10, afterwards it takes corresponding sound where randomly generated number is the position in the list and plays it.

The problem is what should I feed my MediaPlayer with in the bold area? MediaPlayer mpfn = MediaPlayer.create(getActivity(),R.raw.number1);

I'm new to android, and sorry in advance in case my question hurt your feelings. Thanks in advance.

2 Answers2

1

Assuming the media files are stored in raw folder, you can play the songs in random this way:

First generate random number using Math.random() . Then play the corresponding music, this way:

    Random ran = new Random();
    int x = ran.nextInt(3);
    if(x==0)
    {
        mPlayer = MediaPlayer.create(this,R.raw.fst);
    }
    else if(x==1)
    {
        mPlayer = MediaPlayer.create(this,R.raw.sec);
    }
    else if(x==2)
    {
        mPlayer = MediaPlayer.create(this,R.raw.thd);
    }
    length = 0;
    try{mPlayer.prepare();}catch (Exception e){}

This shows how you can play randomly from 3 media files, the process for 10 files is no different. once its ready, you can play it using : mPlayer.start();

OBX
  • 5,586
  • 6
  • 25
  • 67
0

At last I can answer this question myself. This was very simple to achieve, I've made string-array and stored all my sounds there in my own order. So whenever I got my random number I've been just picking this number and used it as item index in that string array.