android play one sound at a time - android

I am stumped on this and I have referenced so many other posts. I'm not asking for anyone to complete my code but simply to point out where I'm going wrong and steer me into the right direction. I want to play an audio file when I click a image button but have it stop when another image button is clicked. The problem I'm having is if I press all the image buttons they will all play audio at the same time.
package com.application.cats.catsshapecolorapp;
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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_page);
mpPurple = MediaPlayer.create(context, R.raw.purpleaudiotest);
ImageButton purpleB = (ImageButton) findViewById(R.id.purpleButton);
purpleB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpPurple.isPlaying()) {
mpPurple.stop();
mpPurple.release();
mpPurple = MediaPlayer.create(context, R.raw.purpleaudiotest);
} mpPurple.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpBlue = MediaPlayer.create(context, R.raw.blueaudiotest);
ImageButton blueB = (ImageButton) findViewById(R.id.blueButton);
blueB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpBlue.isPlaying()) {
mpBlue.stop();
mpBlue.release();
mpBlue = MediaPlayer.create(context, R.raw.blueaudiotest);
} mpBlue.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpRed = MediaPlayer.create(context, R.raw.redaudiotest);
ImageButton redB = (ImageButton) findViewById(R.id.redButton);
redB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpRed.isPlaying()) {
mpRed.stop();
mpRed.release();
mpRed = MediaPlayer.create(context, R.raw.redaudiotest);
} mpRed.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpGreen = MediaPlayer.create(context, R.raw.greenaudiotest);
ImageButton greenB = (ImageButton) findViewById(R.id.greenButton);
greenB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpGreen.isPlaying()) {
mpGreen.stop();
mpGreen.release();
mpGreen = MediaPlayer.create(context, R.raw.greenaudiotest);
} mpGreen.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpYellow = MediaPlayer.create(context, R.raw.yellowaudiotest);
ImageButton yellowB = (ImageButton) findViewById(R.id.yellowButton);
yellowB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpYellow.isPlaying()) {
mpYellow.stop();
mpYellow.release();
mpYellow = MediaPlayer.create(context, R.raw.yellowaudiotest);
} mpYellow.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
mpPink = MediaPlayer.create(context, R.raw.pinkaudiotest);
ImageButton pinkB = (ImageButton) findViewById(R.id.pinkButton);
pinkB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mpPink.isPlaying()) {
mpPink.stop();
mpPink.release();
mpPink = MediaPlayer.create(context, R.raw.pinkaudiotest);
} mpPink.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
}
update: now the problem is the pinkaudiotest is always the first audio file to play no matter what image button I click. I have to click a second time to hear the correct audio file.

You are creating a new MediaPlayer instance every click. Simply use a single one.
if (media.isPlaying()) {
media.stop();
media.release();
media= MediaPlayer.create(context, R.raw.purpleaudiotest);
} media.start();

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.

onResume does not work after app is minimized

I have everything else working fine but when I minimize that app and then go back and try to resume my image buttons will not play the audio files associated with them. I have to go back to the start screen of the app and go back to the activity page with the image buttons just to get them to play the audio again. any hints would help.
public class ColorPage extends AppCompatActivity {
Context context = this;
MediaPlayer media = null;
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(media!=null){
media.stop();
media.release();
media = null;
}
}
#Override
protected void onResume() {
super.onResume();
if(media == null) {
media.start();
}
}
#Override
protected void onPause() {
super.onPause();
if(media != null) {
media.pause();
media.release();
media = null;
}
}
this is the code I'm using. everything else seems to work except the onResume().
I also used if(media != null) but all it did was cause the last audio file to play automatically every time I opened the activity page. If(media == null) was just the last thing I tried.
#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 != null) {
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 != null) {
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 != null) {
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 != null) {
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 != null) {
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 != null) {
media.stop();
media.release();
media = MediaPlayer.create(context, R.raw.pinkaudiotest);
}
media.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
This is the rest of the code for the class ColorPage so my question is a bit more clear.
Your checks in the each of the color button onClick only initialize the media when it is not null, (very strange) and in this case it also happens to be the problem. Your onPause nulls out the media, and onResume doesn't reinitialize it, so that if (media!=null) is always false, in fact, you probably gets npe on media.start() after that. handle the click like so.
if (media != null) {
media.stop();
media.release(); // release previous media if not null
}
// initialize this outside of the if block
media = MediaPlayer.create(context, R.raw.pinkaudiotest); // whatever color in each
media.start();
You've set media to null in onPause, assuming you want to just start where the audio has left off onResume. If you don't want to automatically start, there doesn't seem to be a point to implement onResume at all.
#Override
protected void onResume() {
super.onResume();
if(media != null) {
media.start();
}
}

How to start MediaPlayer after it has been stopped in android

I am new to Android and in my app I am working with MediaPlayer.
When I first tap the start button, the song plays, but when I tap the stop button and then I tap on the start button again, the song does not start playing again. Here's what I have so far:
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
final MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
}
});
}
}
Try this :
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
}
});
just check like this way
if(mdpl.isPlaying()){
mdpl.pause();
} else {
mdpl.start();
}
You can not call start, it media player in on stop state. Take a look on the state diagram of media player MediaPlayer state diagram.
When you call stop, you have to call release(), and with start you get a new media player, or just call reset.
try this
public void onStopBtnClick(View view) {
if (mAudioHelper != null) {
mAudioHelper.stop();
displayMessage("Stopping!");
}
}
Here is code to set sound file.
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = new MediaPlayer();
AppLog.d("Created new Media player");
try {
mPlayer.setDataSource(fileName);
} catch (IOException e) {
AppLog.e("Can't open " + fileName + " file", e);
}
Before playing u should call the mPlayer.prepareAsync() function.
if you want to pause/play you have to use this code:
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
If you want to stop player use this:
if (mPlayer != null){
mPlayer.stop();
mPlayer.release();
}
mPlayer = null;
If you want to start song again use first functions and next with this steps
This code may help you..
#Override
protected void onDestroy() {
super.onDestroy();
destroyMediaPlayer();
}
private void destroyMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
Log.d("here", "destroy");
} catch (Exception e) {
e.printStackTrace();
}
}
}
SOLUTION 1
for this solution, I took some info from here
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
MediaPlayer mp;
/**
* remain false till media is not completed, inside OnCompletionListener make it true.
*/
private boolean initialStage = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (initialStage) {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
new Player()
.execute("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} else {
if (mp && !mp.isPlaying())
mp.start();
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp && mp.isPlaying())
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.stop();
mp.release();
mp = null;
initialStage = true;
}
}
});
}
/**
* preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread.
* #author piyush
*
*/
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mp.setDataSource(params[0]);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
initialStage = true;
mp.stop();
mp.reset();
}
});
mp.prepare();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mp.start();
initialStage = false;
}
public Player() {
progress = new ProgressDialog(PlayngUrlFiles.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
this.progress.show();
}
}
}
SOLUTION 2
in order to avoid data downloding, try this
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
boolean prepared;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
final MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
prepared = false;
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
prepared = true;
mp.start();
}
});
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
try {
if(!prepared) {
mp.prepareAsync();
prepared = true;
} else {
mp.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.pause();
}
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.stop();
prepared = false;
}
}
});
}
}
#MRodrigues was right about media player states. But instead of calling release() after stop, Modify your code as below.
Currently,
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
modify to,
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mp.isPlaying()) {
mp.prepare();
}
mp.start();
}
});

Radio streaming android

Hi I want to implement a radio in my application...I wrote this code, it worked in the emulator YouWave but il dosen't worked in a SmartPhone and another tablet and I don't know why..can you help me please?
This is the code of the radio :
public class radio extends Activity {
MediaPlayer media;
Button buttonplay;
Button buttonStopRecord;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radio);
buttonStopRecord = (Button) findViewById(R.id.Stop);
buttonStopRecord.getBackground().setAlpha(150);
buttonStopRecord.setEnabled(false);
buttonStopRecord.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view) {
if ( media.isPlaying() ) {
media.stop();
}
}
});
buttonplay = (Button) findViewById(R.id.play);
buttonplay.getBackground().setAlpha(150);
buttonplay.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view) {
try
{
media = new MediaPlayer();
media.setAudioStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
media.setDataSource("http://indiespectrum.com:9000");
media.prepare();
media.start();
if ( media.isPlaying()) {
buttonplay.setEnabled(false);
buttonStopRecord.setEnabled(true);
}
}
catch(Exception e)
{
//Getting Exception
}
}
});
Button accueil=(Button)findViewById(R.id.accueilr);
accueil.getBackground().setAlpha(200);
accueil.getBackground().setAlpha(150);
accueil.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view) {
try{
if ( media.isPlaying() ) {
media.stop();
}
}catch (Exception e)
{
Intent i=new Intent(radio.this,main.class);
startActivity(i);
}
Intent i=new Intent(radio.this,main.class);
startActivity(i);
}
});
}
}
From what I know this code should work on every device with Api higher than 8.
media = new MediaPlayer();
media.setAudioStreamType(AudioManager.STREAM_MUSIC);
media.setDataSource("http://indiespectrum.com:9000");
media.prepareAsync();
media.seOnPreparedListener(this);
And inside the OnPrepared method put media.start(). This worked for me.

Android Media Player play/pause Button

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

Categories

Resources