Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 217
Santhosh Avatar asked Aug 02 '26 06:08

Santhosh


1 Answers

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();

like image 194
Cris Grange Avatar answered Aug 03 '26 23:08

Cris Grange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!