简体   繁体   中英

How to avoid sounds from overlapping when I press Next button using Fragments? (Android Studio)

I am using Fragments in Android Studio and each Fragment contains some educational lessons. I decided to put voice over in it so that the users can listen to the voice overs instead of reading the lessons alone. I use MediaPlayer by the way. However, when I press the Next button to proceed to the next page, the sounds overlap. The previous sound doesn't stop which overlaps with the next sound.

Here is my code:

package com.pau.papsirehv.knowledge;


import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;


public class Fragment1 extends Fragment {

    TextView next;
    ViewPager viewPager;
    Button btnSound;

    public Fragment1() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        btnSound = (Button)getActivity().findViewById(R.id.btnSound);
        MediaPlayer mp = MediaPlayer.create(getActivity().getApplicationContext(), R.raw.two);
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
        viewPager = getActivity().findViewById(R.id.viewPager);

        next = view.findViewById(R.id.slideOneNext);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1);
               mp.start();
            }


        });
        return view;
    }
}

When I press the Next button, the previous sound should stop and the sound from the Next page starts. Can you guys give me some code to follow?

You should change the media source or else create MediaPlayer every time next button press. Your next button code looks like...

next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           mp.setDataSource(getApplicationContext(), myUri);
           mp.prepare();
           viewPager.setCurrentItem(1);
           mp.start();               
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM