1

当用户先前选择的声音正在播放时,如何停止该声音并立即播放新选择的声音?到目前为止,我的代码只会停止新声音,但用户必须再次选择声音才能播放它。

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 多种声音的音板。我需要对我的代码进行哪些(我认为是轻微的)更改?任何帮助将不胜感激!

4

1 回答 1

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;
            }
        });
    }
}
于 2013-04-06T21:26:17.227 回答