lundi 20 mars 2017

Pick random sound from array to play on button click on Android Studio

I want to select a random sound from an array

<array name="cat_sounds">
    <item>@raw/cat_1</item>
    <item>@raw/cat_2</item>
    <item>@raw/cat_3</item>
</array>

and to play that sound on button click.

//Cat button sounds
TypedArray cat_sounds = getResources().obtainTypedArray(R.array.cat_sounds);
int choice = (int) (Math.random() * cat_sounds.length());

Button cat = (Button) this.findViewById(R.id.catSounds);
final MediaPlayer mp = MediaPlayer.create(this,cat_sounds[choice]);
cat.setOnClickListener(new OnClickListener() {
 public void onClick(View v){
        mp.start();
    }
});

But for some reason, my code makes my application to crash. What's wrong??




Aucun commentaire:

Enregistrer un commentaire