Reputation: 305
i want to play audio files(MP3) by clicking on Item view , but the problem that i want the previous file to stop automatically when i click on the other one and so on.
public ViewHolder(View itemView) {
super(itemView);
itemImage =(ImageView)itemView.findViewById(R.id.item_image);
itemTitle =(TextView)itemView.findViewById(R.id.item_title);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
stopPlaying();
mp = MediaPlayer.create(v.getContext(), sounds[position]);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null&&mp.isPlaying()) {
mp.stop();
mp.release();
mp = null;
}
}
the audio file still running while playing the other one.
Upvotes: 1
Views: 911
Reputation: 1210
Well, according to e.g. MVP pattern, I'd suggest you to move all the sound-playing logic out of the ViewHolder. The simpliest solution is to create listener, passed to Adapter which will notify some sort of manager:
public interface PlayerListener {
void soundChanged(Object sound);
}
Than you can create Adapter like this (whatever your sound object is)
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
(...)
Object[] sounds;
PlayerListener playerListener;
public Adapter(Object[] sounds, PlayerListener playerListener) {
this.sounds = sounds;
this.playerListener = playerListener;
}
@Override
public void onBindViewHolder(ViewHolderholder, int position) {
holder.bind(playerListener, (...) );
}
public ViewHolder(View itemView) {
public void bind(playerListener, (...)) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
soundChanged(sounds[position]);
}
}
}
}
}
Of course while creating Adapter object you have to pass the reference of object implementing PlayerListener. This object can easly handle sound switching simply storing reference to current MediaPlayer object.
public class SoundPlayer implements PlayerListener {
MediaPlayer currentMediaPlayer;
@Override
public void soundChanged(Object sound) {
stopPlaying();
currentMediaPlayer= MediaPlayer.create(context, sound);
currentMediaPlayer.start();
}
private stopPlaying() {
if (currentMediaPlayer!= null && currentMediaPlayer.isPlaying()) {
currentMediaPlayer.stop();
currentMediaPlayer.release();
currentMediaPlayer= null;
}
}
}
Hope this helps! :)
Upvotes: 1
Reputation: 15718
I doubt you have declared MediaPlayer in ViewHolder.
If you declared MediaPlayer in ViewHolder it will create a different instance for each item in your ViewHolder, so when stopPlaying() is called it is accessing new instance which might not be playing so it wont stop.
Declare the MediaPlayer Globally or Activity or in Adapter - pass the instance of MediaPlayer to Viewholder and try the same it should work.
Upvotes: 0