samedi 24 octobre 2015

Android - Play Random Sounds on Button Click

i am very new in "coding" for Googles Android.

At the moment i am programming a small app with one button. If you click on it, it plays a random sound. BUT :D ... it plays a sound, on every start an other. But no random sounds if you press the button often.

I dont know where is my mistake.

Here is the code (don't laugh!):

public class MainActivity extends Activity {

//MediaPlayer
MediaPlayer mp;
ImageButton soundbutton;

//Sounds
int[] sounds={R.raw.s1, R.raw.s2, R.raw.s3, R.raw.s4, R.raw.s5, R.raw.s6, R.raw.s7, R.raw.s8, R.raw.s9, R.raw.s10};
Random r = new Random();
int Low = 0;
int High = 10;
int rndm = r.nextInt(High-Low) + Low;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);

    //MediaPlayer
    soundbutton = (ImageButton)this.findViewById(R.id.randomsoundbutton89);
    mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
    soundbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                if (mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                    mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
                }
                mp.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

}

Help! (from Germany)!




Aucun commentaire:

Enregistrer un commentaire