Santhosh
Santhosh

Reputation: 11774

Android: using mediaplayer inside recyclerview

I want to use mediaplayer in each item of my recycler view. I want to play audio immediately on a particular item when its shown.

I am trying:

public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int i) {
vhplaymusic = (PersonViewHolderplaymusic) viewHolder;
mp = MediaPlayer.create(viewHolder.itemView.getContext(), Uri.parse(context.getExternalFilesDir("krishna").getPath() + "/amalharinaam_finalcut_loud.mp3"));
mp.start();
}

when in try to run, It says mp is null.

logcat for the error:

E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: com.simha.sacredindaapp, PID: 29281
E/AndroidRuntime: java.lang.NullPointerException
E/AndroidRuntime:     at com.simha.yatras.Myplanshowrvadapter.onBindViewHolder(Myplanshowrvadapter.java:410)
E/AndroidRuntime:     at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5217)
E/AndroidRuntime:     at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5250)
E/AndroidRuntime:     at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4487)
E/AndroidRuntime:     at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4363)

Upvotes: 4

Views: 3288

Answers (2)

Mazhar Iqbal
Mazhar Iqbal

Reputation: 999

You can use the media player in recyclerview by doing:

       MediaPlayer animalTrack = 
       MediaPlayer.create(holder.itemView.getContext(),R.raw.r1);
                animalTrack.start();
                animalTrack.setLooping(true);

Upvotes: 0

Cris Grange
Cris Grange

Reputation: 50

In order to create a new MediaPlayer, you should do it in the following way:

MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(context.getExternalFilesDir("krishna").getPath() + "/amalharinaam_finalcut_loud.mp3"));
mPlayer.prepareAsync();

Using prepareAsync() you won't block the application while the audio is being loaded, so we need a callback method to reproduce the audio once it's loaded:

mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mPlayer) {
                            Common.dismissLoading(progressDialog);
                            if (mPlayer != null) {
                                mPlayer.start();
                            }
                        }
                    });

After that, you can handle pauses and resumes with mPlayer.start(); and mPlayer.pause(); ; and finally, when you don't want the audio anymore mPlayer.release();

Upvotes: 1

Related Questions