RecyclerView

时间:2018-05-06 16:00:39

标签: java android android-mediaplayer

我有一个RecyclerView,显示歌曲列表,我已经成功实现了点击监听器,并使用日志进行验证。现在我想在点击活动中播放这首歌。当我第一次点击一个项目时,歌曲开始播放,但如果我然后点击任何其他项目该应用程序只是崩溃

这是我的RecyclerViewClickListener

SongAdapter songAdapter = new SongAdapter(getContext(), songsList, new RecyclerViewClickListener() {
        @Override
        public void onClick(View view, int position) {
            Toast.makeText(getContext(), "You clicked on Ssong "+songsList.get(position).getSongName(), Toast.LENGTH_SHORT)
                    .show();
            songPath = songsList.get(position).getUrl();
            Log.v("Song Path", songPath);
            if(mp.isPlaying())
                releaseMediaResources();
            playSong();
        }
    });
recyclerView.setAdapter(songAdapter);

这是我的playSong方法

private void playSong () {
        if(!songPath.equals("")) {
            try {
                mp.setDataSource(songPath);
            } catch (Exception e) {
                Log.e("Home Fragment", "Error setting song Url", e);
            }
            mp.prepareAsync();
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.stop();
                    mp.reset();
                    mp.release();
                }
            });
        }
    }

这是我的releaseMediaResources

private void releaseMediaResources() {
    mp.stop();
    mp.reset();
    mp.release();
}

这些是错误

java.lang.IllegalStateException
    at android.media.MediaPlayer.isPlaying(Native Method)
    at com.ashutosh.prototype4.HomeFragment.playSong(HomeFragment.java:159)
    at com.ashutosh.prototype4.HomeFragment.releaseMediaResources(HomeFragment.java:192)
    at com.ashutosh.prototype4.HomeFragment.access$100(HomeFragment.java:31)
    at com.ashutosh.prototype4.HomeFragment$2.onClick(HomeFragment.java:94)
    at com.ashutosh.prototype4.SongAdapter$1.onClick(SongAdapter.java:50)

据我所知,主要的问题在于设置媒体播放器,因为当我只显示Toast消息时,根本没有任何问题,但只要我实现媒体播放器的点击方法就会发生崩溃

1 个答案:

答案 0 :(得分:0)

我会每次创建新的MediaPlayer,但当然会尝试检查,如果还没有现有的实例:

private MediaPlayer mediaPlayer;

private void playSong(String filePath) {
    if (mediaPlayer != null && mediaPlayer.isPlaying()){
        mediaPlayer.stop();
    }

    mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(filePath));
    mediaPlayer.setVolume(DEFAULT_VOLUME_MUSIC, DEFAULT_VOLUME_MUSIC);
    mediaPlayer.start();
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {

        }
    });
}