dimanche 9 juillet 2017

"Android app" Play random sound on button [duplicate]

This question already has an answer here:

I tried many ways to make it happen, but every time i failed. I want to play random sound on button click, using "wav" format sound from res/raw folder. Here is my code:

public class PointsCalculator extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calculator_points);

    List<Integer> soundList = new ArrayList<Integer>();
    soundList.add(R.raw.a1);
    soundList.add(R.raw.b2);


    Button addPlayerPts1 = (Button) findViewById(R.id.addPlayerPts1);
    addPlayerPts1.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View view) {

            EditText playerPts1 = (EditText) findViewById(R.id.playerPts1);
            TextView playerPtsResult1 = (TextView) findViewById(R.id.playerPtsResult1);

            int num1 = Integer.parseInt(playerPts1.getText().toString());
            int num0 = Integer.parseInt(playerPtsResult1.getText().toString());
            int result = num1 + num0;
            playerPtsResult1.setText(result + "");

            playRandomSound();

        }
    });

    private void playRandomSound() {

    int randomInt = (new Random().nextInt(soundList.size()));
    int sound = soundList.get(randomInt);
        MediaPlayer mp = MediaPlayer.create(this, sound);
    mp.start();
        }
}
}




Aucun commentaire:

Enregistrer un commentaire