H3XXX
H3XXX

Reputation: 647

Android sound only plays once

I was making an app in java for android, and whenever a button is clicked, a sound plays. It works fine but pressing the button once makes it play, and then pressing that button or any other button doesn't do anything.

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

Button s1, s2, s3, s4;
MediaPlayer ss1, ss2, ss3, ss4;

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

    s1 = (Button) findViewById(R.id.s1);
    s2 = (Button) findViewById(R.id.s2);
    s3 = (Button) findViewById(R.id.s3);
    s4 = (Button) findViewById(R.id.s4);

    s1.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            ss1 = MediaPlayer.create(MainActivity.this, R.raw.sound1);
            ss1.start();
        }
    });

    s2.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            ss2 = MediaPlayer.create(MainActivity.this, R.raw.sound2);
            ss2.start();
        }
    });

    s3.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            ss3 = MediaPlayer.create(MainActivity.this, R.raw.sound3);
            ss3.start();
        }
    });

    s4.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){
            ss4 = MediaPlayer.create(MainActivity.this, R.raw.sound4);
            ss4.start();
        }
    });



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}  

How can I fix this?

Upvotes: 0

Views: 1036

Answers (1)

MDMalik
MDMalik

Reputation: 4001

Why don't you try this way
Only use one MediaPlayer and reuse it. Something like this

    MediaPlayer ss1;
    s1 = (Button) findViewById(R.id.s1);
    s2 = (Button) findViewById(R.id.s2);
    s3 = (Button) findViewById(R.id.s3);
    s4 = (Button) findViewById(R.id.s4);


    s1.setOnClickListener(new View.OnClickListener(){       
           public void onClick(View v){
                ss1= new MediaPlayer();
                ss1= MediaPlayer.create(this, R.raw.sound1);
                ss1.prepare();
                ss1.start();

        }
    });

Upvotes: 2

Related Questions