Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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):</p> <ul> <li><p>You seem to be doing a lot more work per click than you need to. You're creating and adding a new <code>onClickListener</code> for every click <em>in the Activity's View, not the Button</em>. 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.</p></li> <li><p>Regarding your error, MediaPlayer works fine for me when the Context I pass it is the overriding Activity. When you pass <code>this</code>, it's passing the <code>onClickListener</code> you are creating, throwing off the MediaPlayer.</p></li> <li><p>Finally, to actually play the sound, you have to call <code>start()</code>.</p></li> </ul> <p>So for the constructor in the Activity, you can create the <code>MediaPlayer</code> once, find the Button, and attach an <code>onClickListener</code> that will play the sound from the MediaPlayer you've just created. It would look something like:</p> <pre><code>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(); } }); } } </code></pre> <p>Hope that helps!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload