Mediaplayer - stop current audio when clicking on new audio - android

Im a newbie to android studio (programming at general) but i want to build a mediaplayer for learning purposes.
I have a a list of local music in a listView that contains 2 images 'play, pause and stop button'.
This is how my app works:
Click on playbutton -> start music
Click on pausebutton -> pause music
Click on stopbutton -> stop music
Very simple. BUT! the thing is -> when i pause a song and want to play another song in my list then it just resume the first song i clicked on.
I want it to release the first song and start the other one i click on.
This is my code:
// play music
viewHolder.playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (flag) {
//get song you clicked on
mediaPlayer = MediaPlayer.create(context, song.getSong());
//set boolean to false so it can get ANOTHER song when
//clicked
flag = false;
Toast.makeText(context, "Playing" + song.getName(),
Toast.LENGTH_LONG).show();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.playB.setImageResource(R.drawable.play);
} else {
mediaPlayer.start();
viewHolder.playB.setImageResource(R.drawable.pause);
}
}
});
// stop
viewHolder.stopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!flag) {
mediaPlayer.stop();
mediaPlayer.release();
flag = true;
}
viewHolder.playB.setImageResource(R.drawable.play);
}
});

Your logic is a little bit wrong. When you create the MediaPlayer you set flag to false and as long as you do not stop playback flag doesn't change. But your MediaPlayer creation depends on it.
For future improvements (maybe when you're more confident in working with MediaPlayer and Android) you should take a look at a more "self-made" approach instead of MediaPlayer.create(...) cause this method is calling MediaPlayer's prepare() method that is going to eventually make your app extremely slow or crash it when loading big files.
Example according to comments
I assumed songis going to be the class object.
// class variable will hold the currently loaded song
private Song mCurrentSong;
[...]
viewHolder.playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// MediaPlayer has not been initialized OR clicked song is not the currently loaded song
if (mCurrentSong == null || song != mCurrentSong) {
// Sets the currently loaded song
mCurrentSong = song;
mediaPlayer = MediaPlayer.create(context, song.getSong());
Toast.makeText(context, "Playing" + song.getName(),
Toast.LENGTH_LONG).show();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.playB.setImageResource(R.drawable.play);
} else {
mediaPlayer.start();
viewHolder.playB.setImageResource(R.drawable.pause);
}
}
});
viewHolder.stopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// If currently loaded song is set the MediaPlayer must be initialized
if (mCurrentSong != null) {
mediaPlayer.stop();
mediaPlayer.release();
mCurrentSong = null; // Set back currently loaded song
}
viewHolder.playB.setImageResource(R.drawable.play);
}
});

Related

How to stop multiple songs playing at same time?

I have a list of songs i put manually inside my app and it currently have 3 functions: start, pause and stop (using ImageViews).
The problem is that i can play multiple songs at the same time that is not supposed to be like that. I really cant find the issue here and hope someone can help.
This is a demonstration on my problem
I want it to STOP currently playing song when another song is being clicked on.
Here is my code for my play button:
viewholder.playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentSong == null || song != currentSong) {
currentSong = song;
mediaPlayer = MediaPlayer.create(context, song.getSong());
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewholder.playB.setImageResource(R.drawable.play_black);
} else {
mediaPlayer.start();
viewholder.playB.setImageResource(R.drawable.pause_black);
}
}
});
Instead of always creating a new instance of MediaPlayer every time the event onClick is called, you should create a single instance and reused it.
To play a new song don't forget to reset your player first. Here is an example:
mPlayer.reset();
mPlayer.setDataSource(context, song.getSong());

Hello. I'm making a lyrics app which can also play the music of the lyrics

what I'm trying to do is add 1 button that will play and stop the music. is it possible to loop them like 1st click play then 2nd click stop 3rd click will start from beginning and 4th stops again and so on?
based on my search on google it's something like this? sorry if noob question
public void playtd(View view) {
if(!td.isPlaying()) {
td.start();
}
else if(td.isPlaying()) {
td.pause();
}
}
Try This:
MediaPlayer td;
boolean isPrepared;
public void prepareMediaPlayer(Uri yourTrackUri){
// call this on initialization of your mediaplayer
sMRMediaPlayer = MediaPlayer.create(mContext, uri);
sPrepared = true;
}
public void playtd(View view) {
if (!isPrepared) {
prepareMediaPlayer(Uri yourTrackUri)
}
if(!td.isPlaying()) {
td.start();
else {
// reprepare mediaplayer
td = MediaPlayer.create(Context, uriToUrFile);
isPrepared = true;
}
} else { // stop playing instead of pause, stop will start playing next time u play from beginning
td.stop();
}
void releaseMediaPlayer() {
if (td!= null) {
Log.d(TAG, "MediaPlayer is released.");
td.reset();
td.release();
td= null;
isPrepared = false;
}
}
call releaseMediaPlayer once done with all play and stop stuff (may be on destroy etc.)
initialize mediaplayer by passing track uri to prepareMediaPlayer
add try catch, wherever needed

How to play/stop/play again using MediaPlayer [duplicate]

This question already has answers here:
Media Player start stop start
(8 answers)
Closed 6 years ago.
I have a button when clicked it plays an audio, and while it is playing I can pause it and replay it again and so forth. I have a shake event, where I want to play the audio on shake and replay it when device is shaken again (by first stopping the audio, calling stopAudio?)
I have the following code:
llBtn = (LinearLayout) findViewById(R.id.button);
llBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(MainActivity.this, "LL WAS CLICKED", Toast.LENGTH_SHORT).show();
//IF AUDIO IS NOT PLAYING... PLAY AUDIO
if (tvPS.getText() == "Stop Phrase!") {
StopAudio();
}
else {
PlayAudio();
}
}
});
//the same button is clicked to stop, it is currently setting to Pause.
public void StopAudio() {
mediaPlayer.pause();
Toast.makeText(MainActivity.this, "STOPPED", Toast.LENGTH_SHORT).show();
tvPS.setText("Play Phrase!");
}
public void PlayAudio() {
//stopPlaying(mediaPlayer);
tvPS.setText("Stop Phrase!");
inResId = getResources().getIdentifier("play" , "raw", getPackageName());
mediaPlayer = MediaPlayer.create(getBaseContext(), inResId);
mediaPlayer.seekTo(0);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_SHORT).show();
tvPS.setText("Play Phrase!");
mediaPlayer.pause();
}
});
}
...
public void onShake() {
// Do stuff!
Toast.makeText(getBaseContext(), "Motion detected",
Toast.LENGTH_SHORT).show();
if (mediaPlayer == null) {
PlayAudio();
}
}
How can I modify the code above to handle Play, and then stop if stopped in the middle and then able to replay it again.
The button click works but I am creating a new instance each time and not recycling. When the device is shaken, it plays the audio twice instead of just once.
First of all create the MediaPlayer in onCreate of the context and not in some listener, and don't forget to release it when done, since it consumes a lot of resources,
mediaPlayer.release();
mediaPlayer = null;
Next thing, stop the audio using the stop() function instead of the pause() on completion of the song.
Steps
If you are using a service/activity to play a video create a MediaPlayer instance before it's usage begins, likely in onCreate.
Later use that instance to play/pause/stop the media.
In the onStop of the Service/Activity release the MediaPlayer instance.
Update your playMusic() function to use the MediaPlayer instance you just created, also in the listener use stop() instead of pause()
To change track of an existing MediaPlayer instance
You can use this:
String path = getExternalFilesDir(null).toString()+"/";
mMediaPlayer.setDataSource(path + mediafile);
Link: Changing data source for audio playback using existing MediaPlayer?

MediaPlayer.start() sound execution delayed

I've a strange problem with my app.
Every time a button is clicked, I call a method to execute sound.
The code:
public static void executeSound(Context context) {
if (isSoundEnabled(context)) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, R.raw.button_click);
}
mediaPlayer.start();
}
}
Where isSoundEnabled function verified if user has sound enabled inside app.
Sound is not executed each time I tap button, but after I tap other buttons, and sounds are executed all together.
So happen that I press three different buttons, and three sounds are executed only when I push a button for third time. How can I execute immediately the sound?
I have this problem on lollipop devices (the same code run perfectly on the same device but with kitkat)
Change your execute method to this
public static void executeSound(Context context) {
if (isSoundEnabled(context)) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(mContext, audioUriPath);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
}

mediaplayer gets hanged

My list consists of 12 songs and it has to move in an infinite loop when the button is clicked.my mediaplayer is working fine in emulator but it is getting stuck if i press the button continuously for 32 times in htc mobile.
public void onClick(View v)
{
if(count==listlen)
count=-1;
if(count<listlen)
{
count=count+1;
}
loadpitch(concatstr);
}
load pitch has this
try
{
if(sp.isChecked()||sm.isChecked())
{
mp.reset();
mp=MediaPlayer.create(this,resID);
mp.setLooping(true);
}
if(play==true)
{
mp.start();
}
}
where listlen is the length of the pre-defined list
loadpitch is function which loads the song
sp and sm are toggle buttons!
check this way for ur media player while starting media player onclick
if (mPlayer!=null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer= MediaPlayer.create(YourActivity.this,song);
mPlayer.start();

Categories

Resources