Jasmin Obradovac Jasmin Obradovac - 9 months ago 29
Android Question

How to make ImageButton repeat a sound each time it's clicked

I am trying to get the Image Button to play a sound each time it's clicked. For example, if the sound is playing for few seconds and I press the button again it should start from the beginning. I managed to get the sound working but it's not repeating it. How can I get it to start over?

ImageButton bt;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
}

Answer Source

Try this:

@Override
public void onClick(View v) {
    try {
        if (mp.isPlaying()) {
            mp.stop();
            mp.release();
            mp = MediaPlayer.create(context, R.raw.bird);
        }
        mp.start();
    } catch(Exception e) { 
        e.printStackTrace(); 
    }
}