0

我有一个布局,其中显示了多个按钮。onclick 按钮分别播放一个声音。我的代码就像但它不起作用:-

@Override
public void onClick(View view) {
    resetPlayer();
    int index = 0;
    if (view.equals(objbutton1))
        index = R.raw.sound1;

    while (true) {
        this.objplayer = MediaPlayer.create(this, index);
        this.objplayer.setLooping(false);
        this.objplayer.start();
        this.objplayer
                .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        MainActivity.this.objplayer.release();
                        MainActivity.this.objplayer = null;

                    }
                }
                );
        if(view.equals(objbutton2))
        {
            index=R.raw.sound2;
            continue;

        }
        if(view.equals(objbutton3))
        {
            index=R.raw.sound3;
            continue;

        }
        if(view.equals(objbutton4))
        {
            index=R.raw.sound4;
            continue;

        }
        if(view.equals(objbutton5))
        {
            index=R.raw.sound5;
            continue;

        }
        break;
    }

}

private void resetPlayer() {
    if (this.objplayer != null) {
        if (this.objplayer.isPlaying())
            this.objplayer.stop();
        this.objplayer.release();
        this.objplayer = null;
    }

应用程序仅播放一种声音,单击其他按钮时不会更改声音

4

1 回答 1

0

用这个

 MediaPlayer mp = MediaPlayer.create(getApplicationContext(), index);
                    mp.start();

像...

 private MediaPlayer mp; // declare it in public area.

    public void onClick(View view) {
    int index = 0;
    if (view.equals(objbutton1)){
        index = R.raw.sound1;
            if(mp !=null && mp.isPlaying()) mp.stop();
        mp = MediaPlayer.create(getApplicationContext(), index);
            mp.start();
        }
        if(view.equals(objbutton2))
        {
            index=R.raw.sound2;
            if(mp !=null && mp.isPlaying()) mp.stop();
        mp = MediaPlayer.create(getApplicationContext(), index);
            mp.start();
        }
        if(view.equals(objbutton3))
        {
            index=R.raw.sound3;
          if(mp !=null && mp.isPlaying()) mp.stop();
          mp = MediaPlayer.create(getApplicationContext(), index);
         mp.start();
        }
        if(view.equals(objbutton4))
        {
            index=R.raw.sound4;
          if(mp !=null && mp.isPlaying()) mp.stop();
          mp = MediaPlayer.create(getApplicationContext(), index);
         mp.start();
        }
        if(view.equals(objbutton5))
        {
            index=R.raw.sound5
          if(mp !=null && mp.isPlaying()) mp.stop();
         mp = MediaPlayer.create(getApplicationContext(), index);
         mp.start();
        }
}

onDestroy()把这个mp.release();

于 2013-04-06T15:12:26.727 回答