gursahib.singh.sahni
gursahib.singh.sahni

Reputation: 1597

play the same sound in android without waiting for the previous to end

guys scenario is that suppose i click a button, the sound plays and within the duration of that track i again click the button and want to play it from the beginning. i tried with the following code, but no success. code is :

public class SoundtestActivity extends Activity {
/** Called when the activity is first created. */
 MediaPlayer mp;
 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
     mp = MediaPlayer.create(this, R.raw.gun_shot);
    Button click=(Button) findViewById(R.id.bt1);
    click.setOnClickListener((new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mp.isPlaying())
                mp.reset();
            mp.start();
        }
    }));
       }

}

Upvotes: 0

Views: 523

Answers (3)

Fahad Ishaque
Fahad Ishaque

Reputation: 1926

Best way and the easiest way is = mp.setLooping(true); And yes it does work, just simply add this line after mp.start() and nothinfg else is required

Upvotes: 1

Fahad Ishaque
Fahad Ishaque

Reputation: 1926

Try this code

mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
                mp.start();
            }

        }); 

Or replace mp.start(); by mp.reset(); in this code

Upvotes: 1

Some one Some where
Some one Some where

Reputation: 777

You just need to comment the following lines and shift your Media player instance in the button's listener method, bingo your done with multiple media players playing parallel to each other

Button click=(Button) findViewById(R.id.bt1);
click.setOnClickListener((new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    mp = MediaPlayer.create(this, R.raw.gun_shot); // ADD THIS LINE HERE

        if(mp.isPlaying()){ 
            mp.stop();           //ADDED TO STOP FIRST
            mp.release();        //ADDED TO RELEASE RESOURCES
    }
        mp.start();
    }
}));

Upvotes: 0

Related Questions