RecyclerView中的音乐播放按钮

时间:2016-12-15 19:02:39

标签: android android-recyclerview android-mediaplayer android-adapter

我正在使用RecyclerView并希望能够通过按下按钮来播放歌曲,但我不知道如何实现这一目标。以下是我的适配器的代码:

public void onBindViewHolder(final RingtoneViewHolder holder, final int position) {
    final RingtoneItem ringtoneItem = ringtoneItems.get(position);
    holder.downloadCount.setText(String.valueOf(position + 1) + "+ " + ringtoneItem.getId());
    if (ringtoneItems.get(position).isFav()) {
      holder.play.setImageResource(R.mipmap.ic_pause_circle_filled_black_24dp);
    } else {
      holder.play.setImageResource(R.mipmap.ic_play_circle_filled_black_24dp);
    }
    mediaPlayer = new MediaPlayer();
    holder.play.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        if (!ringtoneItems.get(position).isFav()) {
          holder.play.setImageResource(R.mipmap.ic_pause_circle_filled_black_24dp);
          ringtoneItems.get(position).setFav(true);


        } else {
          holder.play.setImageResource(R.mipmap.ic_play_circle_filled_black_24dp);
          ringtoneItems.get(position).setFav(false);


        }
      }
    });
}

我尝试使用媒体播放器,但双击播放按钮后发生了崩溃:

 mediaPlayer.setDataSource(context, Uri.parse(ringtoneItem.getUrl()));
  mediaPlayer.prepareAsync();

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

         if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.prepareAsync();
            animation.cancel();
            holder.play.setImageResource(R.mipmap.ic_play_circle_filled_black_24dp);
            holder.progressBar.setVisibility(View.INVISIBLE);
          } else {
            mediaPlayer.start();
            animation = ObjectAnimator.ofInt(holder.progressBar, "progress", 0, 500);
            selected_item = 1;
            animation.setDuration(mediaPlayer.getDuration());
            animation.setInterpolator(new DecelerateInterpolator());
            animation.start();
            holder.play.setImageResource(R.mipmap.ic_pause_circle_filled_black_24dp);

            holder.progressBar.setVisibility(View.VISIBLE);
            if (formatDuration(mediaPlayer.getCurrentPosition()) == formatDuration(mediaPlayer.getDuration())) {
              holder.progressBar.setVisibility(View.INVISIBLE);
            }

          }

  });
} catch (IOException e) {
  e.printStackTrace();
}

0 个答案:

没有答案