如何在recyclerView中自动播放歌曲?

时间:2017-10-06 12:09:57

标签: java android android-recyclerview android-music-player

我正在构建一个音乐播放器应用程序,并使用sd卡中的歌曲填充了recyclerView。我也设置了onClickListeners。所以当我点击一个项目(歌曲)时,该特定位置的歌曲开始播放。我想要的是当它完成播放时,我想让下一首歌像现代音乐播放器一样自动播放。我知道我必须使用OnCompletionListener,但我无法理解。

我是Android的新手。

Songs.java(这是一个片段):

public class Songs extends Fragment {

public static final String Broadcast_PLAY_NEW_AUDIO = "com.musicplayer.musicana.PlayNewAudio";
public static final String TAG = "Songs";
RecyclerView recyclerView;
private ArrayList<SongInfoModel> SongList = new ArrayList<SongInfoModel>();
SongAdapter songAdapter;
ScaleInAnimationAdapter alphaAdapter;
MediaPlayer mediaPlayer;
MainActivity mainActivity;
private MediaPlayerService player;
boolean serviceBound = false;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.songs_activity, container, false);

  //  Activity activity = getActivity();

    final MainActivity activity=(MainActivity)getActivity();


    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(linearLayoutManager);


    songAdapter = new SongAdapter(getContext(), SongList, new SongAdapter.RecyclerItemClickListener() {
        @Override
        public void onClickListener(SongInfoModel song, int position) {

            Toast.makeText(getContext(), song.getSongName(), Toast.LENGTH_SHORT).show();

            Activity activity = getActivity();
            if (activity instanceof MainActivity) {

                mainActivity = (MainActivity) activity;
                mainActivity.setsongText(song);
                ((MainActivity) activity).ButtonPause();

            }
            prepareSong(song);



        }

        @Override
        public void onLongClickListener(SongInfoModel song, int position) {
            Toast.makeText(getContext(), "You long clicked me, thank you!", Toast.LENGTH_SHORT).show();
        }


    });

    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
    Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                Long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                Long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
                Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);



                SongInfoModel s = new SongInfoModel(name, artist, null, null, null, duration, data,albumArtUri);
                SongList.add(s);

            } while (cursor.moveToNext());
        }


        cursor.close();

        Collections.sort(SongList, new Comparator<SongInfoModel>() {
            @Override
            public int compare(SongInfoModel lhs, SongInfoModel rhs) {
                return lhs.getSongName().compareTo(rhs.getSongName());
            }
        });



    }


    alphaAdapter = new ScaleInAnimationAdapter(songAdapter);
    alphaAdapter.setDuration(1000);
    alphaAdapter.setInterpolator(new OvershootInterpolator());
    alphaAdapter.setFirstOnly(false);
    recyclerView.setAdapter(alphaAdapter);
    alphaAdapter.notifyDataSetChanged();


    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);



    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {

            togglePlay(mp);
        }
    });

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {




        }
    });

    activity.setOnSongClickListener(new MainActivity.OnSongCickListener() {
        @Override
        public void onsongClicked() {
            if(mediaPlayer.isPlaying() && mediaPlayer!=null ){

                mediaPlayer.pause();
                activity.ButtonPlay();


            } else {

                mediaPlayer.start();
                activity.ButtonPause();

            }
        }
    });




    return view;
}




private void prepareSong(SongInfoModel song) {


    mediaPlayer.reset();


    try {
        mediaPlayer.setDataSource(song.getData());
        mediaPlayer.prepareAsync();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void togglePlay(MediaPlayer mp) {

    if (mp.isPlaying()) {
        mp.stop();

        mp.reset();
    } else {

        mp.start();


    }


}

SongAdapter.java(recyclerVIews adapter):

public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongHolder> {

ArrayList<SongInfoModel> SongList = new ArrayList<>();
Context context;
private RecyclerItemClickListener listener;





public SongAdapter(Context context, ArrayList<SongInfoModel> SongList, RecyclerItemClickListener listener) {

    this.context = context;
    this.SongList = SongList;
    this.listener = listener;

}




@Override
public SongAdapter.SongHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.row_song, parent, false);
    return new SongHolder(view);
}

@Override
public void onBindViewHolder(final SongAdapter.SongHolder holder, final int position) {



    final SongInfoModel songInfoModel = SongList.get(position);

    if(songInfoModel!= null){

     holder.songName.setText(songInfoModel.SongName);
     holder.artistName.setText(songInfoModel.ArtistName);
     holder.duration.setText(String.valueOf(songInfoModel.duration));
     String duration = Utility.convertDuration(songInfoModel.getDuration());
     holder.duration.setText(duration);
        Picasso.with(context).load(songInfoModel.getAlbumID()).placeholder(R.drawable.ic_launcher).into(holder.iv_artwork);

        holder.bind(songInfoModel, listener);
    }

}

@Override
public int getItemCount() {
    return SongList.size();
}

public class SongHolder extends RecyclerView.ViewHolder  {
    TextView songName;
    TextView artistName;
    TextView duration;
    private ImageView iv_artwork;


    public SongHolder(View itemView)    {

        super(itemView);
        songName = (TextView)itemView.findViewById(R.id.SongName);
        artistName= (TextView)itemView.findViewById(R.id.ArtistName);
        duration = (TextView) itemView.findViewById(R.id.duration);
        iv_artwork = (ImageView) itemView.findViewById(R.id.iv_artwork);

    }

    public void bind(final SongInfoModel songInfoModel, final RecyclerItemClickListener listener) {
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onClickListener(songInfoModel, getLayoutPosition());

            }
        });

        itemView.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View view) {

                listener.onLongClickListener(songInfoModel, getLayoutPosition());
                return true;
            }
        });

    }



}




public interface RecyclerItemClickListener{

   void onClickListener(SongInfoModel song, int position);
    void onLongClickListener(SongInfoModel song, int position);

}







}

2 个答案:

答案 0 :(得分:2)

您可以像这样使用Media Player的完成侦听器

mediaPlayer.setOnCompletionListener(new OnCompletionListener(){

        public void onCompletion(MediaPlayer mp) {
           //pass the path of the new song here
        }
    });

答案 1 :(得分:0)

我刚刚找到了解决方案!很容易!

在SongAdapter.java中:添加此内容,

private int selectedPosition;

 public void setSelectedPosition(int selectedPosition) {
    this.selectedPosition = selectedPosition;
}

public int getSelectedPosition() {
    return selectedPosition;
}

在Songs.java中:添加此内容,

 private void changeSelectedSong(int index){
    songAdapter.notifyItemChanged(songAdapter.getSelectedPosition());
    currentIndex = index;
    songAdapter.setSelectedPosition(currentIndex);
    songAdapter.notifyItemChanged(currentIndex);

}


mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {



            if(currentIndex + 1 < SongList.size()){
                SongInfoModel next = SongList.get(currentIndex + 1);
                changeSelectedSong(currentIndex+1);
                prepareSong(next);
                mainActivity.setsongText(next);
            }else{
                SongInfoModel next = SongList.get(0);
                changeSelectedSong(0);
                prepareSong(next);
                mainActivity.setsongText(next);
            }



        }
    });

并在onClick中调用changeSelectedSong(position)。