如何播放声音时,被点击的Andr​​oid按钮?按钮、声音、Andr、oid

2023-09-13 23:47:09 作者:陌路

我想打一个按钮被点击时声音文件,但不断收到一个错误。

I'm trying to play a sound file when a button is clicked but keeps getting an error.

该错误是:

 "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new View.OnClickListener(){}, int)"

下面是我的code:

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Button zero = (Button)this.findViewById(R.id.btnZero);
    zero.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mp = MediaPlayer.create(this, R.raw.mamacita_zero);
        }
    });
}

任何帮助或提示,将AP preciated。 日Thnx!

Any help or tips would be appreciated. Thnx!

推荐答案

有几件事会在这里(免责声明,这是多么我已经习惯使用它,有可能是一个更好的方法):

There are a few things going on here (disclaimer, this is just how I'm used to using it, there may be a better way):

您似乎在做每次点击更多的工作比你需要。你创建和添加一个新的 onClickListener 每次点击的在活动的看法,而不是按钮的。你只需要设置监听器一次,并为按钮,而不是总体视图;我倾向于做,在活动的构造。

You seem to be doing a lot more work per click than you need to. You're creating and adding a new onClickListener for every click in the Activity's View, not the Button. You only need to set the listener once, and for the Button rather than the overarching View; I tend to do that in the constructor of the Activity.

关于你的错误,MediaPlayer的工作正常,我当上下文我通过这是压倒一切的活动。当你通过,它传递 onClickListener 正在创建,摆脱了MediaPlayer的。

Regarding your error, MediaPlayer works fine for me when the Context I pass it is the overriding Activity. When you pass this, it's passing the onClickListener you are creating, throwing off the MediaPlayer.

最后,实际播放声音,你必须调用的start()

Finally, to actually play the sound, you have to call start().

因此​​,对于活动中的构造函数,你可以创建的MediaPlayer 键,找到按钮,并附加了 onClickListener 将播放从MediaPlayer的你刚刚创建的声音。它看起来是这样的:

So for the constructor in the Activity, you can create the MediaPlayer once, find the Button, and attach an onClickListener that will play the sound from the MediaPlayer you've just created. It would look something like:

public class MyActivity extends Activity {

    public MyActivity(Bundle onSavedStateInstance) {
        // eliding some bookkeepping

        MediaPlayer mp = MediaPlayer.create(this, R.raw.mamacita_zero);

        Button zero = (Button)this.findViewById(R.id.btnZero);
        zero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
    }
}

希望帮助!