Roey Cohen
Roey Cohen

Reputation: 339

Android - play the same sound from the beginning at each button click

i create simple code with button and sound file (mp3) , now , when i am pressing at the button , the sound file is playing , but if i am pressing it several times (fast) , it just being playing for first click and till the mp3 ends...i want each click to play the sound from the beginning.

public class TrafficLightsActivity extends Activity implements OnClickListener {


private ImageButton Upbutton ;
private ImageButton Downbutton ;
private ImageView Image ;

private MediaPlayer mp1 ;
private MediaPlayer mp2 ;


int counter=5 ;



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


    Upbutton = (ImageButton) findViewById (R.id.button1) ;
    Downbutton = (ImageButton) findViewById (R.id.button2) ;
    Image = (ImageView) findViewById(R.id.imageView1) ;

    mp1 = MediaPlayer.create(this, R.raw.nextsound) ;
    mp2 = MediaPlayer.create(this, R.raw.backsound) ;



    Upbutton.setOnClickListener(this) ; 
    Downbutton.setOnClickListener(this) ; }

@Override
    public void onClick(View v) {



        if (Upbutton == v){
            if (mp1.isPlaying()){
                mp1.stop() ;
            }
            counter= counter+1 ;
            System.out.println("Number of clicks is: " + counter) ;
            mp1.start();


        }   }

Upvotes: 1

Views: 73

Answers (2)

Karthika PB
Karthika PB

Reputation: 1373

try this way

@Override
public void onClick(View v) {

   if(mp1!=null){

         try{


                mediaPlayer.stop();
                mediaPlayer=null;
                mediaPlayer.release();

            }
            }
            catch(IllegalStateException e){

                //System.out.println(e);
            }
            catch(Exception e){

                //System.out.println(e);
            }
 else{

    mp1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

        @Override
        public void onPrepared(MediaPlayer mp) {
            // TODO Auto-generated method stub


            mp.start();

        }
    });


    mp1.setOnCompletionListener(new      MediaPlayer.OnCompletionListener() {             

    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        mp.release();
    }
});

}

Upvotes: 0

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

You can call seekTo(0) method that will let to replay the sound from the start without finishing the sound:

if (Upbutton == v){
        if(mp1.isPlaying())
            mp1.seekTo(0);
        mp1.start();
    } 

Upvotes: 1

Related Questions