简体   繁体   English

在Android Studio中播放声音的按钮不播放

[英]Button that Plays Sound in Android Studio not Playing

I am trying to make a simple button that plays a sound, but I am getting an error on (this, R.raw.shotgun) . 我正在尝试制作一个播放声音的简单按钮,但是我收到了一个错误(this, R.raw.shotgun) I have the raw folder and the sound file. 我有raw文件夹和声音文件。 I think the problem is with the this but I don't know why. 我认为问题在this但我不知道为什么。 Thanks. 谢谢。

public class MainActivity extends AppCompatActivity {

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

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mp = MediaPlayer.create(this, R.raw.shotgun);
                mp.start();
            }
        });
    }
}

The first parameter of MediaPlayer.create is a Context . MediaPlayer.create的第一个参数是Context The usage of MediaPlayer.create(this, R.raw.shotgun) works when you are working in your Activity s scope, because Activity extends Context , therefore this in this case ends up being a Context as well. 的使用MediaPlayer.create(this, R.raw.shotgun)当你在你的工作的工作Activity适适用范围,因为Activity扩展Context ,因此this在这种情况下,最终被一个Context也是如此。

However, you're working within View.OnClickListener scope, and this assumes this class' value, and not Context as required. 但是,您正在View.OnClickListener范围内工作,并且this假设此类的值,而不是必需的Context To fix that, just set the Context variable to this while still in your Activity scope. 要解决这个问题,只需将Context变量设置this值,同时仍在Activity范围内。

public class MainActivity extends AppCompatActivity {

private Button button;
Context context;

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

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MediaPlayer mp = MediaPlayer.create(context, R.raw.shotgun);
            mp.start();
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM