每次按下使用android studio的按钮时,如何让1个按钮播放随机声音

时间:2022-09-25 15:26:33
public class MainActivity extends AppCompatActivity { 
MediaPlayer mp; 
ImageButton soundbutton; 

//This is sounds being added

//这是添加的声音

int[] sounds ={R.raw.yeet1, R.raw.yeet2, R.raw.yeet3, R.raw.yeet4, R.raw.yeet5, R.raw.yeet6, R.raw.yeet7, R.raw.yeet8, R.raw.yeet9, R.raw.yeet10, R.raw.yeet11, R.raw.yeet12, R.raw.yeet13}; 
Random r = new Random(); 
int Low = 0; 
int High= 13; 
int rndm = r.nextInt(High-Low) + Low; 

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

//creating the Mediaplayer

//创建Mediaplayer

    soundbutton = (ImageButton) this.findViewById(R.id.button_view); 
    mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]); 
    soundbutton.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View view) { 
            try { 
                if (mp.isPlaying()) { 
                    mp.stop(); 
                    mp.release(); 
                    rndm = r.nextInt(High - Low) + Low; 
                    mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]); 
                } 
                mp.start(); 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
        }

This code wont run and i'm not sure whats causing it thanks for helping!

这段代码不会运行,我不知道是什么导致它感谢帮助!

1 个解决方案

#1


1  

When mp is not playing the if block is not executed.
Change to this:

当mp没有播放时,if块没有被执行。改为:

@Override
public void onClick(View view) {
    try {
        if (mp.isPlaying()) {
            mp.stop();
            mp.release();
        }
        rndm = r.nextInt(High - Low) + Low;
        mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]);
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

#1


1  

When mp is not playing the if block is not executed.
Change to this:

当mp没有播放时,if块没有被执行。改为:

@Override
public void onClick(View view) {
    try {
        if (mp.isPlaying()) {
            mp.stop();
            mp.release();
        }
        rndm = r.nextInt(High - Low) + Low;
        mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]);
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}