LewTrocki
LewTrocki

Reputation: 41

Playing random sound when ImageButton is clicked on Android

I'm new in android and I'm trying to play random sound when ImageButton is clicked.

I'm still getting the same audio when I press the button. It should play different sounds every time the button is pressed. Also I would like to add a stop button later.

Here is my code:

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;

import java.util.Random;

public
class MainActivity extends AppCompatActivity {

    MediaPlayer mp;
    ImageButton soundbutton;

    int[] sounds = {R.raw.audi, R.raw.berlin, R.raw.bratanki, R.raw.budzik, R.raw.cztery, R.raw.drzyz, R.raw.dziewczyny, R.raw.emeryt, R.raw.enter, R.raw.faza};
    Random r = new Random();
    int rndm = r.nextInt();

    @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);

        //media player

        soundbutton = (ImageButton)this.findViewById(R.id.playButton);
        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();
                        rndm = r.nextInt();
                        mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]);
                    }
                    mp.start();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Thank you for your help.

Upvotes: 1

Views: 76

Answers (1)

Trevor Soare
Trevor Soare

Reputation: 120

You need to give a maximum to your Random. You have 10 sounds so you want a number between 0-9.

rndm = r.nextInt(10); 

This will give you a number between 0-9.

Upvotes: 1

Related Questions