我每次使用Android Studio按下按钮时如何使1个按钮播放随机声音

时间:2018-08-12 19:08:49

标签: java android android-studio audio random

public class MainActivity extends AppCompatActivity { 
MediaPlayer mp; 
ImageButton soundbutton; 

//这是要添加的声音

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

///创建媒体播放器

    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(); 
            } 
        }

此代码无法运行,我不确定是什么原因导致的!

1 个答案:

答案 0 :(得分:1)

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();
    }
}