媒体播放器无法正常工作

时间:2014-12-16 13:25:12

标签: java android

我正在制作和应用程序,你按下按钮播放声音。它似乎首先工作,但在5-6按下后它停止播放声音。这是我的代码

public class MainActivity extends ActionBarActivity {


private ImageButton pad1, pad2, pad3, pad4, pad5, pad6, pad7, pad8, pad9, pad10, pad11, pad12;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pad1 = (ImageButton) findViewById(R.id.pad1);
    pad2 = (ImageButton) findViewById(R.id.pad2);
    pad3 = (ImageButton) findViewById(R.id.pad3);
    pad4 = (ImageButton) findViewById(R.id.pad4);
    pad5 = (ImageButton) findViewById(R.id.pad5);
    pad6 = (ImageButton) findViewById(R.id.pad6);
    pad7 = (ImageButton) findViewById(R.id.pad7);
    pad8 = (ImageButton) findViewById(R.id.pad8);
    pad9 = (ImageButton) findViewById(R.id.pad9);
    pad10 = (ImageButton) findViewById(R.id.pad10);
    pad11 = (ImageButton) findViewById(R.id.pad11);
    pad12 = (ImageButton) findViewById(R.id.pad12);


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}



    public void onPad1Click(View view) {
        MediaPlayer mp = MediaPlayer.create(this, R.raw.p1);
        mp.start();
    }

public void onPad2Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p2);
    mp.start();
}

public void onPad3Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p3);
    mp.start();

}

public void onPad4Click(View view) {

    MediaPlayer mp = MediaPlayer.create(this, R.raw.p4);
    mp.start();
}

public void onPad5Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p5);
    mp.start();
}

public void onPad6Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p6);
    mp.start();
}

public void onPad7Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p7);
    mp.start();
}

public void onPad8Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p8);
    mp.start();
}

public void onPad9Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p9);
    mp.start();
}

public void onPad10Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p10);
    mp.start();
}

 public void onPad11Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p11);
     mp.start();
}

 public void onPad12Click(View view) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.p12);
   mp.start();
}
}

我不知道它可能是什么声音很短,所以我不认为这是问题所在。我希望有人可以帮助解决这个问题。谢谢!

1 个答案:

答案 0 :(得分:0)

我建议使用SoundPool而不是MediaPlayer进行短暂播放。

添加以下变量:

SoundPool soundPool = null;
int sound1_id;
int sound2_id;

添加到你的onCreate() - 方法(而不是MediaPlayer):

soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
sound1_id = soundPool.load(this, R.raw.p1, 1);
sound2_id = soundPool.load(this, R.raw.p2, 1);

并在特定的onClick():

soundPool.play(sound1_id, (float) 0.5, (float) 0.5, 1, 0, 1.f);