简体   繁体   English

在Android(Java)中一首一首的播放歌曲

[英]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.例如,它正在播放歌曲A,然后它会播放下一首歌曲B,但在歌曲B之后它不会播放歌曲C。

Here is my code:这是我的代码:

OnCompleteListener: 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:播放歌曲 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.我尝试删除mp.reset()mp.release()mp = null但它仍然只播放了下一首歌曲。

It looks like you want a Queue data structure, hopefully is gonna be easier to handle than keeping track of indexes.看起来你想要一个Queue数据结构,希望它比跟踪索引更容易处理。 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.您的al变量将存储要播放的歌曲队列,在您的onCompletion方法中,您可以调用playNextSong()方法,该方法使用poll()remove()处理队列以获取下一首歌曲并播放直到队列为空。

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.如果您想保留您的 ArrayList,请尝试调试您的song_nosong变量以缩小问题是否出在歌曲顺序逻辑或 MediaPlayer 使用中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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