Search code examples
javaandroidandroid-viewpagerandroid-mediaplayer

Mediaplayer respond to second click to pause


Used ViewPager for images sliding, each image onclick stream different MP3.

app including 50 pages(images) & 50 different mp3, all mp3 stored on app itself.

ex. First-page stream MP3(one), second-page stream MP3(two) and so on till page fifty.

FIRST:

its work fine just only one issue which is:

In any page --> clicking the image --> 

 PLAY MP3(one) --> click again--> PAUSE MP3 -->
 in paused state of MP3(one) SWIPE to next page --> 

--> in next page --> clicking the image -->
  PLAY MP3(two) --> click to pause the MP3(two)

   --> it doesn't respond to first click,it respond to second click to pause MP3(two).

SECOND:

the app contain 50 pages and 50 different MP3, does i need to repeat the mediaplayer code 50 times which i already did , or there is better approach to do that in single code applied to all 50 mediaplayer MP3 , as all has the same function cycle.

any advice please and how to apply it in coding .

MainActivity :

public class MainActivity extends Activity {

private ViewPager mViewPager;
MediaPlayer mp;
private boolean isPaused;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mViewPager= (ViewPager) findViewById(R.id.view_pager);
    ImageAdapter adapter = new ImageAdapter(this);
    mViewPager.setAdapter(adapter);

    final GestureDetector tapGestureDetector = new GestureDetector(this, new TapGestureListener());
    mViewPager.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            tapGestureDetector.onTouchEvent(event);
            return false;
        }
    });
}

private class TapGestureListener extends GestureDetector.SimpleOnGestureListener {
    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        if (mViewPager.getCurrentItem() == 0) {
            if (mp != null) {
                if (isPaused) {
                    mp.start();
                    isPaused = false;
                } else {
                    mp.pause();
                    isPaused = true;
                }
            } else {
                mp = MediaPlayer.create(MainActivity.this, R.raw.aa);
                mp.start();

                    }
                }

        if (mViewPager.getCurrentItem() == 1) {
            if (mp != null) {
                if (isPaused) {
                    mp.start();
                    isPaused = false;
                } else {
                    mp.pause();
                    isPaused = true;
                }
            } else {
                mp = MediaPlayer.create(MainActivity.this, R.raw.bb);
                mp.start();                  
            }
        }

        if (mViewPager.getCurrentItem() == 2) {
            if (mp != null) {
                if (isPaused) {
                    mp.start();
                    isPaused = false;
                } else {
                    mp.pause();
                    isPaused = true;
                }
            } else {
                mp = MediaPlayer.create(MainActivity.this, R.raw.cc);
                mp.start();                 
            }
        }

        if (mViewPager.getCurrentItem() == 3) {
            if (mp != null) {
                if (isPaused) {
                    mp.start();
                    isPaused = false;
                } else {
                    mp.pause();
                    isPaused = true;
                }
            } else {
                mp = MediaPlayer.create(MainActivity.this, R.raw.dd);
                mp.start();
            }
        }
      //AND SO ON FOR 50 PAGES//  
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {   
                if (mp == null) {
                    return;
                }
                mp.release();
                mp = null;
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub                  
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
            }
        });

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer m) {
                Toast.makeText(MainActivity.this, 
                        "COMPLETED", Toast.LENGTH_LONG).show();
                // Set the MainActivity member to null
                MainActivity.this.mp = null;
            }
        });

        return super.onSingleTapConfirmed(e);
       }
   }
}

ImageAdapter:

  public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
    R.drawable.a,
    R.drawable.b,
    R.drawable.c,
    R.drawable.d,

};
ImageAdapter(Context context){
    this.context=context;
}
@Override
public int getCount() {
  return GalImages.length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
  return view == ((ImageView) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
  ImageView imageView = new ImageView(context);
  int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
  imageView.setPadding(padding, padding, padding, padding);
  imageView.setScaleType(ImageView.ScaleType.CENTER);
  imageView.setImageResource(GalImages[position]);
  ((ViewPager) container).addView(imageView, 0);
  return imageView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
  ((ViewPager) container).removeView((ImageView) object);
   }
 }

I'm new to android, I tried to fix it but with no success, its simple app just includes MainActivity & ImageAdapter.

i tried the below code also still the issue not resolved:

  mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {   
                if (mp != null) {
                    if (mp.isPlaying()) {
                        mp.stop();
                    }
                    mp.release();
                    mp = null;
                }
            }
            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub                  
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
            }
        });

UPDATE:

In any page:

let’s say page (one) ---> click to play MP3 ---> (playing) ---> click to pause MP3 ---> (paused) ---> swipe to any page Rt or Lf --->( swiped to page (two) for example ) ---> click to play MP3 on page (two) ---> (playing) ---> click to pause MP3 on page (two) ---> (paused) ---> (all previous onclick action working correctly) ---> click to resume playing MP3 in page (two) which already in paused state ====> BUT mistakenly when you click the image in page (two) to resume playing the MP3 , your finger not straight , its slightly tilted so the finger click lead to ( click on page (two) and in the same time swipe to page (three) ====> here is the issue the page (three) MP3 start playing by itself from the beginning .

I want if this happened occasionally or mistakenly not to start playing the MP3 in page (three) until I click the image in page (three) then start playing the MP3.

any help will be really appreciated.


Solution

  • First Questions answer:-

    Just copy paste this code and let me know I have not tested it but have a strong feeling it will work.

    import java.lang.reflect.Field;
        public class MainActivity extends Activity {
    
            private ViewPager mViewPager;
            MediaPlayer mp;
            private boolean isPaused;
            private ArrayList<Integer> mMp3s;
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
    
                mViewPager = (ViewPager) findViewById(R.id.view_pager);
                ImageAdapter adapter = new ImageAdapter(this);
                mMp3s=getAllMp3FilesFromRaw();
                mViewPager.setAdapter(adapter);
    
                final GestureDetector tapGestureDetector = new GestureDetector(this, new TapGestureListener());
                mViewPager.setOnTouchListener(new View.OnTouchListener() {
                    public boolean onTouch(View v, MotionEvent event) {
                        tapGestureDetector.onTouchEvent(event);
                        return false;
                    }
                });
            }
    
            private class TapGestureListener extends GestureDetector.SimpleOnGestureListener {
                @Override
                public boolean onSingleTapConfirmed(MotionEvent e) {
    
                        if (mp != null) {
                            if (isPaused) {
                                mp.start();
                                isPaused = false;
                            } else {
                                mp.pause();
                                isPaused = true;
                            }
                        } else {
                            mp = MediaPlayer.create(MainActivity.this, mMp3s.get(mViewPager.getCurrentItem()));
                            mp.start();
                            isPaused = false;
                        }
    
    
                    //AND SO ON FOR 50 PAGES//
                    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                            if (mp == null) {
                                return;
                            }
                            mp.release();
                            mp = null;
                            isPaused = true;
                        }
    
                        @Override
                        public void onPageScrollStateChanged(int arg0) {
                            // TODO Auto-generated method stub
                        }
    
                        @Override
                        public void onPageScrolled(int arg0, float arg1, int arg2) {
                            // TODO Auto-generated method stub
                        }
                    });
    
                    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        public void onCompletion(MediaPlayer m) {
                            Toast.makeText(MainActivity.this, "COMPLETED", Toast.LENGTH_LONG).show();
                            // Set the MainActivity member to null
                            finish();
                            MainActivity.this.mp = null;
                        }
                    });
    
                    return super.onSingleTapConfirmed(e);
                }
            }
    
            /**
            *Do it on background thread if it blocks the UI.
            */
            private ArrayList<Integer> getAllMp3FilesFromRaw() {
                ArrayList<Integer> mp3s = new ArrayList<>();
                try {
                    Field fields[] = R.raw.class.getDeclaredFields();
                    for (int i = 0; i < fields.length; i++) {
                        Field f = fields[i];
    
                        int resIdentifier = getResources().getIdentifier(f.getName(), "raw", getPackageName());
                        mp3s.add(resIdentifier);
                    }
                    return mp3s;
    
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
    

    The logic is get all the mp3 files resource id when you start the app if this process is taking too much time do it on background thread.

    using those resorce id play your songs now there much be some issue with the list which you fetch like they may not match with your image or viewpager number for that you will have to apply some other logic if you encounter any error let me know.

    Sec Questions answer:- Now I presume that when you want to click on the image to play the music at the same time by mistake page is getting swiped and when it reached to other page it start playing that page's music immediately. If I understood you question as I still don't know which code are you using I ll guide you through the methods based on that you can apply the logic.

    when page changes to next one then

    onPageChanged(int position)
    

    method will be called https://stackoverflow.com/a/11294494/5492047 here you can apply the logic. Now how, if the music is playing and you are on the first page and you swiped on to the second one what you have to do in

    onPageChanged(int position)
        {
         mp.release();
         mp=null;
        //Now initialiase it again with page two's music.
        mp = MediaPlayer.create(MainActivity.this, R.raw.aa);
        }
    

    and don't call mp.start(); now when user clicks on the image in

     OnClickListener(View view){
        //use the same instance of mediaplayer and call mp.start();
        if(isPlaying){
           mp.pause();
        }else{
        mp.start();
     }
    }
    

    I assume you are using only one instance of MediaPlayer not like you have shown in your code.