我想在我的应用程序上添加一个按钮。我想:当我点击按钮,随机播放声音。我输入了这些代码,但是当我运行项目模拟器时,它正在关闭
public class MainActivity extends Activity {
//MediaPlayer
MediaPlayer mp;
ImageButton soundbutton;
//Sounds
int[] sounds={R.raw.s1, R.raw.s2, R.raw.s3, R.raw.s4, R.raw.s5, R.raw.s6, R.raw.s7, R.raw.s8, R.raw.s9, R.raw.s10};
Random r = new Random();
int Low = 0;
int High = 10;
int rndm = r.nextInt(High-Low) + Low;
@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);
//MediaPlayer
soundbutton = (ImageButton)this.findViewById(R.id.randomsoundbutton89);
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(High-Low) + Low;
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
}
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
暂无答案!
目前还没有任何答案,快来回答吧!