Good day! In the application, when flipping through a picture (ViewPager), there is music (there is music for each picture), that is, if the second picture opens, the first music should turn off, and the second one should start, and so on. Now when turning over, the first one does not turn off, the second one turns on, then the third one, etc. I tried, but I can not think of how to make a normal condition for MediaPlayer. Help me please! Here is the code MainActivity.java:

public class MainActivity extends AppCompatActivity { public static MediaPlayer mp=null; ViewPager viewPager; CustomSwipeAdapter adapter; private int[] mAudio=new int[]{R.raw.sound_1,R.raw.sound_2,R.raw.sound_3}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = (ViewPager) findViewById(R.id.view_pager); adapter = new CustomSwipeAdapter(this); viewPager.setAdapter(adapter); viewPager.setOnPageChangeListener(mOnPageListener); } public OnPageChangeListener mOnPageListener=new OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} @Override public void onPageSelected(int position) { mp= MediaPlayer.create(MainActivity.this,mAudio[position]); mp.start(); } @Override public void onPageScrollStateChanged(int state) {} }; 

}

    1 answer 1

    They are not turned off, because the code does not register the stop of playback when changing the tab. In onPageSelected you need to add a stop to the playback in the previous open tab, or, in order not to suffer from the calculations, just stop all the tracks, because the right one will start in the method.