媒体播放器无法通过按钮点击方式播放声音

时间:2014-03-31 15:31:10

标签: java android audio android-mediaplayer media

我有3个按钮,他们应该播放3种不同的声音。当我在oncreate方法中使用3个单独的onclicks方法时它工作正常,但我想稍微清理一下代码,所以我将OnClickListener实现为acvtivity并将onclick方法向下移动。但现在,媒体播放器不播放声音。我怎样才能确保媒体播放器有效?

public class Play extends Activity implements OnClickListener {

    MediaPlayer mpPlay1,mpPlay2,mpPlay3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play);


    Button bPlay1 = (Button) findViewById(R.id.button1);
    Button bPlay2 = (Button) findViewById(R.id.button2);
    Button bPlay3 = (Button) findViewById(R.id.button3);

        int resIdPlay1 = getResources().getIdentifier("play1", "raw", getPackageName());
        int resIdPlay2 = getResources().getIdentifier("play2", "raw", getPackageName());
        int resIdPlay3 = getResources().getIdentifier("play3", "raw", getPackageName());

        mpPlay1 = MediaPlayer.create(this, resIdPlay1);
        mpPlay2 = MediaPlayer.create(this, resIdPlay2);
        mpPlay3 = MediaPlayer.create(this, resIdPlay3);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.button1:
            mpPlay1.start();
            break;
        case R.id.button2:
            mpPlay2.start();
            break;
        case R.id.button3:
            mpPlay3.start();
            break;

        }

    }

}

1 个答案:

答案 0 :(得分:2)

您尚未在Buttons上实现侦听器,或者至少未显示该侦听器。你应该有像

这样的东西
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(this);
onCreate()之后setContentView()内的

。每个Button都需要这个。

由于您正在尝试清理代码并使其更加精简,因此您可以在xml中设置onClick()

我已解释过它in this answerthis one

The Button docs also cover this