1

I have tried to play a sound clip on my button click following this link from Stackoverflow

Still now, I can't successfully play the sound clip. What I have here is a simple button's click event which enables a button to play a sound. Can anyone help me to find out what's being wrong here?

Here is the button click listener I am using

MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button btn = (Button)findViewById(R.id.button1);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mp = MediaPlayer.create(MainActivity.this, R.raw.sc);
            mp.setLooping(true);
            mp.start();
            btn.setSoundEffectsEnabled(true);
            mp.release();
        }
    });
}

and here is the XML code

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:soundEffectsEnabled="true"
        android:layout_marginTop="41dp"
        android:text="Button" />

</RelativeLayout>

Thanks in advance

Community
  • 1
  • 1
user3673503
  • 385
  • 2
  • 6
  • 14

2 Answers2

2

If you play sound clip then

    MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonclick);
    mp.setLooping(true);
    mp.setOnCompletionListener(this);
    mp.start();

try this one and you implement method

@Override
public void onCompletion(MediaPlayer mp) {
    mp.stop();
    mp.release();
}
Divyang Metaliya
  • 1,908
  • 1
  • 12
  • 14
2

Remove Line.

mp.release();

As it is used to.

Releases resources associated with this MediaPlayer object. 
It is considered good practice to call this method when you're done 
using the MediaPlayer
Moubeen Farooq Khan
  • 2,875
  • 1
  • 11
  • 26