Android Media Player play/pause Button - android

In my project, I am playing music file in android media player by using the following code
MediaPlayer mPlayer = MediaPlayer.create(MyActivity.this, R.raw.myfile);
mPlayer.start();
the above is coded in the onclick of the play button.
I want to pause the playback by clicking the same button again.ie) single button for play/pause.
How shall i do this.

You could use simple if-check to handle the pausing. Try this:
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}

Please try this::
final Button bPlay = (Button) findViewById(R.id.bPlay);
MediaPlayer song1 = MediaPlayer.create(tutorialFour.this, R.raw.fluet);
Button bStop = (Button) findViewById(R.id.bStop);
bPlay.setWidth(10);
song1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bPlay.setText("Play");
}
});
bPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
b = true;
if (bPlay.getText().equals("Play") && b == true) {
song1.start();
bPlay.setText("Pause");
b = false;
} else if (bPlay.getText().equals("Pause")) {
x = song1.getCurrentPosition();
song1.pause();
bPlay.setText("Resume");
Log.v("log", "" + x);
b = false;
} else if (bPlay.getText().equals("Resume") && b == true) {
song1.seekTo(x);
song1.start();
bPlay.setText("Pause");
b = false;
}
}
});

Inside the button click check for mediaPlayer.isPlaying(). This will return true if the media player is playing else false.
So now with this, flag value you can make a if statement and switch to play or pause like this,
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
} else {
mediaplayer.start();
}
}
});

Below code takes care of your play/pause button click event along with forward and backward buttons for forward and backward seek on the seekbar provided (which is synchronized with the media track). Currently it plays just ONE song. However, you can add to that. This is my first media player using mediaplayer class, so you might find it a bit primitive. However if you need you can also check out the VideoView examples. It's apparently easier with VideoView as the standard media console is already present in the form of pre-defined widgets. so that makes designing the player much easier.
package in.org.Test;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Toast;
public class Test12Activity extends Activity implements OnClickListener,Runnable {
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
private SeekBar seek;
MediaPlayer player = new MediaPlayer();
private ImageButton plus,minus;
ImageButton im;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton3);
player = MediaPlayer.create(this, R.raw.sound2);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton1);
seek = (SeekBar) findViewById(R.id.seekBar1);
seek.setVisibility(ProgressBar.VISIBLE);
seek.setProgress(0);
seek.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { int cu = player.getCurrentPosition(); player.seekTo(cu-5000); }});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {int cu = player.getCurrentPosition(); player.seekTo(cu+5000);}});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton1) {
if(player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.play);
}
else
{
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.pause);
}
}
}
#Override
public void run() {
int currentPosition= 0; String s;
int total = player.getDuration();
while (player!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek.setProgress(currentPosition);
}
}
}

MediaPlayer mpE = MediaPlayer.create(GuitarTuner.this, R.raw.test2 );
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mpE.isPlaying()) {
mpE.pause();
play.setBackgroundResource(R.drawable.play);
} else {
mpE.start();
play.setBackgroundResource(R.drawable.pause);
}
}
});

For pausing the Mediaplayer:
Mediaplayer.pause();
length = Mediaplayer.getCurrentPosition();
and for resuming the player from the position where it stopped lately is done by:
Mediaplayer.seekTo(length);
Mediaplayer.start();

public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//the song was previously saved in the raw folder. The name of the song is mylife (it's an mp3 file)
final MediaPlayer mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.mylife);
// Play song
Button playButton = (Button) findViewById(R.id.play);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.start(); // no need to call prepare(); create() does that for you
}
});
// Pause song
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.pause();
}
});
// Stop song - when you stop a song, you can't play it again. First you need to prepare it.
Button stopButton = (Button) findViewById(R.id.stop);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.stop();
mMediaPlayer.prepareAsync();
}
});
}
}

button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = button.getText().toString();
if (text.equals("play")){
mediaPlayer.start();
button.setText("pause"); //changing text
}
else if (text.equals("pause")){
mediaPlayer.pause();
button.setText("play"); //changing text
}
}
});

very simple solution. If mediaplayer is playing, display play button and pause the mediaplayer. If not playing, do the opposite.
playBtn.setOnClickListener(view -> {
//events on play buttons
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.play);
} else {
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.pause);
}
});

Related

MediaPlayer plays wrong file on first click

Can someone point out where I am going wrong with this? When I press the image button it always plays pinktestaudio first even if I did not press the corresponding button. I have to press the image button twice to hear the correct sound.This occurs when the page is first loaded, after the first time it seems fine but still something that shouldn't happen.
import android.content.Context;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class ColorPage extends AppCompatActivity {
Context context = this;
//MediaPlayer mpPurple, mpBlue, mpRed, mpGreen, mpYellow, mpPink;
MediaPlayer media = null;
//private static MediaPlayer media = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_page);
ImageButton pinkB = (ImageButton) findViewById(R.id.pinkButton);
ImageButton yellowB = (ImageButton) findViewById(R.id.yellowButton);
ImageButton purpleB = (ImageButton) findViewById(R.id.purpleButton);
ImageButton blueB = (ImageButton) findViewById(R.id.blueButton);
ImageButton greenB = (ImageButton) findViewById(R.id.greenButton);
ImageButton redB = (ImageButton) findViewById(R.id.redButton);
media = MediaPlayer.create(context, R.raw.purpleaudiotest);
purpleB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.purpleaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.blueaudiotest);
blueB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.blueaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.redaudiotest);
redB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.redaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.greenaudiotest);
greenB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.greenaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.yellowaudiotest);
yellowB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.yellowaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
pinkB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Updated: changing the start of the if statement(all of them) to as follows fixed the issue.
if (media != null) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
}
It always plays pinktestaudio because you have done
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
at the end, so media will always be initialized with pinktestaudio.
even after you click a different button because in every buttons OnClickListener you do
if(media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
}
on clicking any button for first time media.isPlaying() will always be false so
media = MediaPlayer.create(context, R.raw.some_audio_file);
will not be executed.
But when you click again media.isPlaying() is true and all goes well.
In onCreate 6 MediaPlayer instances are created. The last one is used in each of you listeners.
Take a look at your code after refactoring:
public class ColorPage extends AppCompatActivity implements View.OnClickListener {
MediaPlayer mMediaPlayer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_page);
ImageButton pinkB = (ImageButton) findViewById(R.id.pinkButton);
ImageButton yellowB = (ImageButton) findViewById(R.id.yellowButton);
ImageButton purpleB = (ImageButton) findViewById(R.id.purpleButton);
ImageButton blueB = (ImageButton) findViewById(R.id.blueButton);
ImageButton greenB = (ImageButton) findViewById(R.id.greenButton);
ImageButton redB = (ImageButton) findViewById(R.id.redButton);
pinkB.setOnClickListener(this);
yellowB.setOnClickListener(this);
purpleB.setOnClickListener(this);
blueB.setOnClickListener(this);
greenB.setOnClickListener(this);
redB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int audio;
switch (view.getId()) {
case R.id.pinkButton:
audio = R.raw.pinkaudiotest;
break;
case R.id.yellowButton:
audio = R.raw.yellowaudiotest;
break;
case R.id.purpleButton:
audio = R.raw.purpleaudiotest;
break;
case R.id.blueButton:
audio = R.raw.blueaudiotest;
break;
case R.id.greenButton:
audio = R.raw.greenaudiotest;
break;
case R.id.redButton:
audio = R.raw.redaudiotest;
break;
default:
audio = R.raw.purpleaudiotest;
}
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.release();
}
mMediaPlayer = MediaPlayer.create(getApplicationContext(), audio);
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Good luck!
This is because you have assigned the media variable a number of times and the last time it was assigned for pinkaudiotest so to solve your problem you have to assign the variable media inside the events. So it will be assigned only when a button is clicked.
`.
Here is what you are supposed to do using your own same code:
You have SIX lines that looks alike they are of the form of
media = MediaPlayer.create(context, R.raw.purpleaudiotest);
Cut those lines and paste them inside the onClick method of the corresponding Image Button for example. I am going to do the first one for you and repeat it for all SIX times.
purpleB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I AM ADDING IT HERE
media = MediaPlayer.create(context, R.raw.purpleaudiotest); //ADDED INSIDE oClick(View view)
try {
if (media.isPlaying()) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.purpleaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Repeat that for all SIX ImageButton and problem will be gone.

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();
} }
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();
}
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();
}
});
}

How to play and pause in only one button - Android

I have two buttons in my media player that streams a radio station, play and pause. I want to make it only one button that has two function. First click I want to play it and second click I want to pause it. And when I click it again I want to play it. I need help. Here is my code.
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
play.performClick();
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
}
private void play() {
Uri myUri = Uri.parse("Shoutcast URL");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
Create just one Button and add something like a buttonstatus. Then you can check the status in your listener.
For example:
boolean isPlaying = false;
playPause = (Button) findViewById(R.id.play);
playPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (isPlaying) {
pause();
}else{
play();
}
isPlaying = !isPlaying;
}
});
Boolean b = false;
Button play = (Button) findViewById(R.id.play);
play..setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if(b == false)
{
//write play code here
b= true;
}
else
{
// enter pause code here
}
}
}
You can use Toggle button:
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (toggleButton.isChecked()) {
play();
} else {
pause();
}
}
});
You can also remove the green bar from toggle button.
Toggle button Mkyong example
Android dev tutorial
You don't need to declare any boolean variable to check player state. There is a method already available in mediaplayer class named - isPlaying().
Try my code sequence for playpause using single button.
public void playpause(){
if(!mp.isPlaying()){ // here mp is object of MediaPlayer class
mp.start();
//showNotification("Player State Plying");
}
else if(mp.isPlaying()){
mp.pause();
//showNotification("Player State Pause");
}
}

Android MediaPlayer Stop and Play

I'm creating Android application contains 2 buttons, on click on each button play a mp3 file.
The problem is when I play button1 it plays sound1, when I click button2 it plays sound2.
I check on each button the other player if it's working and I stop it and play the clicked one
But If I click on same button twice it's keep first audio playing in the background and play another one again
I tried to check isPlaying() and to stop it, but it doesn't work!
I want If I click on button1 it play sound1 and if clicked on it again it stop it and play it again from beginning.
My code:
package com.hamoosh.playaudio;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PlayaudioActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b= (Button) findViewById(R.id.button1);
Button b2= (Button) findViewById(R.id.button2);
final TextView t= (TextView) findViewById(R.id.textView1);
final MediaPlayer mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
final MediaPlayer mp1 = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp1.isPlaying()) {
mp1.stop();
}
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
}
mp1.start();
}
});
}
}
Hope if there any better code that can use multiple buttons as an array or something to not check each button and player every time.
You should use only one mediaplayer object
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
To stop the Media Player without the risk of an Illegal State Exception, you must do
try {
mp.reset();
mp.prepare();
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}
rather than just
try {
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}
According to the MediaPlayer life cycle, which you can view in the Android API guide, I think that you have to call reset() instead of stop(), and after that prepare again the media player (use only one) to play the sound from the beginning. Take also into account that the sound may have finished. So I would also recommend to implement setOnCompletionListener() to make sure that if you try to play again the sound it doesn't fail.
I may have not got your answer correct, but you can try this:
public void MusicController(View view) throws IOException{
switch (view.getId()){
case R.id.play: mplayer.start();break;
case R.id.pause: mplayer.pause(); break;
case R.id.stop:
if(mplayer.isPlaying()) {
mplayer.stop();
mplayer.prepare();
}
break;
}// where mplayer is defined in onCreate method}
as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception)
Or for better understanding of MediaPlayer you can refer to Android Media Player
just in case someone comes to this question, I have the easier version.
public static MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button);
Button b2 = (Button) findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.game);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
// mp.start();
}
});
}
In Kotlin
1- Upper Class add a variable:
var mpo: MediaPlayer? = null
2- In onCreate or a Function
mpo = MediaPlayer.create(this, R.raw.m7)
mpo!!.start()
3- Add Stop under a control, onClick or any order:
if (mpo != null) {
mpo!!.stop()
mpo!!.release()
mpo = null
}
Note that for each player, need a separate stop!

using only one button to play and pause a Mediaplayer in Android

I am new to Android, my requirement is to use only one button for playing and pause using media player class?
Once you have your MediaPlayer set up, I would just set up in your onCreate() and onResume() methods, a check to see if the MediaPlayer is currently playing (MediaPlayer's isPlaying() method should work for you), and if it is playing, set the button's image and click handler to change it to a pause button. If the MediaPlayer isn't playing, then set it to be a play button.
You'll also need to handle listening for events such as when the MediaPlayer stops (finishes playing the audio file), as well as inverting the button state when you press it (i.e. pressing play changes button to pause, and vice versa).
I would use 2 buttons and hide one of them:
public class MyActivity extends Activity implements View.OnClickListener {
Button playBtn;
Button pauseBtn;
public void onCreate() {
playBtn = (Button) findViewById(R.id.playButton);
pauseBtn = (Button) findViewById(R.id.pauseButton);
playBtn.setOnClickListener(this);
pauseBtn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.playButton:
// play music here
playBtn.setVisibility(Button.GONE);
pauseBtn.setVisibility(Button.VISIBLE);
break;
case R.id.pauseButton:
// pause music here
pauseBtn.setVisibility(Button.GONE);
playBtn.setVisibility(Button.VISIBLE);
break;
}
}
}
you can use a single Imagebutton and change the drawable image , in conjuction with a toggling boolean variable to check the state of the button (play/pause).
This is how I implemented it
ImageButton playButton;
private boolean playOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// some code here
playButton = (ImageButton)findViewById(R.id.btn_play);
//other specifications and your code
}
public void play(View view){
myplayfunction();
}
public void myplayfunction(){
if (playOn){
playOn=false;
playButton.setImageResource(R.drawable.icn_pause);
//your mediaplayer functions
}else{
playOn=true;
playButton.setImageResource(R.drawable.icn_play);
//pause the mediaplayer
}
}
Also, don't forget to toggle your imagebutton at the end, onCompletionListener() method of the mediaplayer
The following code worked for me. The value of the "playedLength" variable should also be initialize to zero, and set the "mediaPlaying" boolean value to false in the media player stop function to avoid errors.
public class MainActivity extends AppCompatActivity {
private Button btnPlay;
private MediaPlayer mPlayer;
private String mFileName = null;
private int playedLength; //variable for the CurrentPosition of audio when paused
private boolean mediaPlaying; // boolean variable for toggling play, pause and resume actions
// some custom codes for my app...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// some custom codes for my app.....
btnPlay = (Button) findViewById(R.id.button_play);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlaying){
mediaPlaying = false;
//pause the media player
mPlayer.pause();
playedLength = mPlayer.getCurrentPosition();
btnPlay.setBackgroundResource(R.mipmap.ic_pause_focused_background);
}else{
mediaPlaying = true;
if(mPlayer == null){
// create the media player
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
btnPlay.setBackgroundResource(R.mipmap.ic_play_focused_background);
} else
// resume playing
mPlayer.seekTo(playedLength);
mPlayer.start();
btnPlay.setBackgroundResource(R.mipmap.ic_play_focused_background);
}
}
});
}
final Button bPlay = (Button)findViewById(R.id.bPlay);
MediaPlayer song1 = MediaPlayer.create(tutorialFour.this, R.raw.fluet);
Button bStop = (Button)findViewById(R.id.bStop);
bPlay.setWidth(10);
song1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bPlay.setText("Play");
}
});
bPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
b=true;
if(bPlay.getText().equals("Play") && b==true)
{
song1.start();
bPlay.setText("Pause");
b=false;
}
else if(bPlay.getText().equals("Pause"))
{
x=song1.getCurrentPosition();
song1.pause();
bPlay.setText("Resume");
Log.v("log",""+x);
b=false;
}
else if(bPlay.getText().equals("Resume") && b==true)
{
song1.seekTo(x);
song1.start();
bPlay.setText("Pause");
b=false;
}
}
});
Button
android:id="#+id/buttonPlay"
android:onClick="Play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="160dp"
android:layout_marginTop="243dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="100dp"
android:text="#string/play"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
//-----------------------------------------------------------------------
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
boolean isPlaing = true;
Button buttonPlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = findViewById(R.id.buttonPlay);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.stuff);
}
public void Play(View view) {
if(isPlaing) {
mediaPlayer.start();
buttonPlay.setText("Pause");
isPlaing = false;
}else {
mediaPlayer.pause();
buttonPlay.setText("Play");
isPlaing = true;
}
}
}

Categories

Resources