Skip to content Skip to sidebar Skip to footer

Implementing Next Button In Audio Player Android

I have been trying to implement next song button in my audio player app. I copied some code from a tutorial but its not working.The button for next song is btnNext and the method i

Solution 1:

Add this in onCreate method:

Bundlebundle= getIntent().getExtras();
position = bundle.getInt("position");

And change next button listener to

btnNext.setOnClickListener(newView.OnClickListener()    //this is the button                                          @OverridepublicvoidonClick(View arg0) {
                   if (mMediaPlayer!= null && mMediaPlayer.isPlaying()) {
                     mMediaPlayer.stop();
                   }
                   uri = Uri.parse(mAudioPath[position + 1]);
                   mMediaPlayer.setDataSource(getApplicationContext(), uri);
                   mMediaPlayer.prepare();              
                   mMediaPlayer.start();
                }
            });

Solution 2:

int currentPosition = 0;
    if (++currentPosition >= songs.size()) {
        currentPosition = 0;
    } elsetry {
                playSong(path + songs.get(currentPosition));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
    }

The above code is your code from the onClick method.

As you can see, you are initializing the currentPosition inside onClick.

So to show you what this implies:

onClick -> position = 0-> position++ (position = 1) ->playSong(songUri)

When you want:

onClick -> position++ -> playSong(songUri)

So, before setting the onCLickListener, you add:

currentPosition = 0;

currentPosition is declared in the class now, so make sure you add it. It should look like this:

int currentPosition;

..other code

publicvoidcde(){
    ..code here
    currentPosition = 0;
   ... set onClickListener
}

Remove int currentPosition = 0; from the onClick method.

I assume there is a position 0 as well. Here is the refactored code that would handle that:

try {
    playSong(path + songs.get(currentPosition));

    if (++currentPosition >= songs.size()) {
        currentPosition = 0;
    } 
} catch (IOException ex) {
    ex.printStackTrace();
}

The above code is addressing another issue you would be likely to meet. Song 0 would never play on the first round.

Another thing you want to check for (not giving you the code for it as it is easy) is to not play or allow next song if there are no songs. If songs.size == 0 it would never play but set the position to 0 over and over.

Post a Comment for "Implementing Next Button In Audio Player Android"