当用户先前选择的声音正在播放时,如何停止该声音并立即播放新选择的声音?我到目前为止的代码只停止了新的声音,但用户必须再次选择声音才能播放。
public class MainActivity extends Activity {
public MediaPlayer mediaPlayer = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.First);
a.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.stop();
}
else {
mediaPlayer.start();
mediaPlayer = null;
}
}
}
);
Button b = (Button) findViewById(R.id.Second);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.secondsound);
mediaPlayer.stop();
}
else {
mediaPlayer.start();
mediaPlayer = null;
}
}
}
);
我正在制作一个超过30种声音的音板,如果这有帮助的话。我需要对我的代码进行哪些(轻微的假设)更改?任何帮助将不胜感激!
答案 0 :(得分:1)
public class MainActivity extends Activity {
public MediaPlayer mediaPlayer = null;
public Boolean playing=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.First);
a.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
(playing)mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.start();
playing=true;
}
});
Button b = (Button) findViewById(R.id.Second);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
(playing)mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.firstsound);
mediaPlayer.start();
playing=true;
}
});
}
}