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();
}
}
此代码无法运行,我不确定是什么原因导致的!
答案 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();
}
}