简体   繁体   中英

Playing songs one after another in Android(Java)

I want to play songs one after another in my music player app. I checked this question but my music player plays the next song only once. After that it stops. For example, it's playing Song A, then it'll play next Song B, but after song B it won't play Song C.

Here is my code:

OnCompleteListener:

//mp is MediaPlayer object, al is ArrayList of songs and their ids(R.raw.song), song_no is the index of the song in al
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                song_no = (song_no +1) % al.size();
                playSong();
            }
        });

I have the same code for "next" button which works perfectly, even after reaching the end of list it loops back. playSong function:

public void playSong()
    {
        song = Uri.parse("android.resource://" + getPackageName() + "/" + al.get(song_no).id());
        try
        {
            mp.stop();
            mp.reset();
            mp.release();
            mp = null;
        }
        catch(Exception e)
        {
            Log.d("playSong", e.toString();
        }
        mp = MediaPlayer.create(getApplicationContext(), song);

        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });
    }

I tried removing mp.reset() , mp.release() and mp = null but it still played the next song only once.

It looks like you want a Queue data structure, hopefully is gonna be easier to handle than keeping track of indexes. Your al variable would store a queue of songs to play, in your onCompletion method you can call a playNextSong() method that handles the queue using poll() or remove() to get the next song and play until the queue is empty.

If you want to keep your ArrayList, Try debugging your song_no and song variables to narrow down if the problem is in the song order logic or the MediaPlayer usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM