我是#34;编码"适用于Googles Android。
目前我正在用一个按钮编写一个小应用程序。如果单击它,它会播放随机声音。但是:D ......它在每次启动时发出声音。但是,如果经常按下按钮,则不会发出随机声音。
我不知道我的错误在哪里。
以下是代码(不要笑!):
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();
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
}
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
帮助! (来自德国)!
答案 0 :(得分:1)
使用此代码获取不同的声音
@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();
}
}
});
}