简体   繁体   中英

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) . I have the raw folder and the sound file. I think the problem is with the this but I don't know why. 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 . 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.

However, you're working within View.OnClickListener scope, and this assumes this class' value, and not Context as required. To fix that, just set the Context variable to this while still in your Activity scope.

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();
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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