mercredi 16 septembre 2020

Play random sound when ImageButton click Android

Im new in android - Im trying to play random sound when ImageButton is clicked. But im getting still the same audio when I press the button. It should play different sound every time when I press the button. Also I would like to add stop Button later. Im a newbie and got little bit lost here. 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.




Aucun commentaire:

Enregistrer un commentaire