媒体播放器在完成第一首歌后播放下一首歌

时间:2018-02-05 13:58:51

标签: java android android-mediaplayer

我想创建一个程序,在一个结束变量后自动播放下一首歌;

String path = "/mnt/sdcard/Music/";
String[] fileArray;
public int songNumber = 0;

MediaPlayer mPlayer = new MediaPlayer();
public boolean isPlaying = false;
public boolean isPaused = false;`

虚空是;

 private void playMusic(String song){
    if(!isPlaying) {
        try {
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mPlayer) {
                    songNumber = songNumber + 1;
                    playMusic("/mnt/sdcard/Music/" + fileArray[songNumber]);
                }

            });

            mPlayer.reset();
            Toast.makeText(getApplicationContext(), song, Toast.LENGTH_SHORT).show();
            mPlayer.setDataSource(song);
            mPlayer.prepare();
            mPlayer.setOnCompletionListener((OnCompletionListener) this);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception of type : " + e.toString());
            e.printStackTrace();
        }

        mPlayer.start();
        isPlaying = true;
    }else{
        stopMusic();
    }
}

然而,在第一首歌结束后没有任何事情发生时没有任何效果

1 个答案:

答案 0 :(得分:0)

将void上的代码更改为此

private void playMusic(String song){
    if(!isPlaying) {
        try {
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mPlayer) {
                    isPlaying = false;
                    mPlayer.reset();
                    songNumber = songNumber + 1;
                    playMusic("/mnt/sdcard/Music/" + fileArray[songNumber]);
                }

            });
            Toast.makeText(getApplicationContext(), song, Toast.LENGTH_SHORT).show();
            mPlayer.setDataSource(song);
            mPlayer.prepare();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception of type : " + e.toString());
            e.printStackTrace();
        }

        mPlayer.start();
        isPlaying = true;
    }else{
        stopMusic();
    }
}

要解决问题