Prathap Gunasekaran
Prathap Gunasekaran

Reputation: 103

Android audio play and stop

this is the method am using..and will call whenever required...in my case i want to control that audio by one button whether it may toggle or button... click to start and stop in one button

private void playSound() {
    if (isFlashLightOn) {
        mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
    } else {
        mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
    }
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

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

}

Upvotes: 0

Views: 43

Answers (2)

Cristofer
Cristofer

Reputation: 1106

Onclick pause:

public void pause(View view) {

            Toast.makeText(getApplicationContext(),
                    "Pausando..", Toast.LENGTH_SHORT)
                    .show();
            if (mp != null && mp.isPlaying()) {
                mp.pause();
            }
        }//pause

Onclik stop-

 public void stop(View view) {
         Toast.makeText(getApplicationContext(),
                "Stop", Toast.LENGTH_SHORT)
                .show();
        if (mp != null) {
            mp.stop();


        }//if
    }//stop

Upvotes: 0

Sakchham
Sakchham

Reputation: 1739

An edited version of your code

private void playSound() {
    if (isFlashLightOn) {
        mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
    } else {
    mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
    }
    mp.prepareAsync(); //prepares the MediaPlayer
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            //MediaPlayer instance prepared
            mp.start();  //play the content
            playing=true;//update the flag
        }
    });
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.release();  //playback finished
            playing=false; //update the flag
        }
    });
}

more info on MediaPlayer here

Upvotes: 1

Related Questions