简体   繁体   中英

play a sound in onClick within a fragment using media player or soundpool

I have 2 image views in a fragment set up as clickable and i am trying to play a sound when each one is clicked! i can do this in an activity but not in a fragment! i am trying to use to media player but this throws up an error.

public class HomeFragment extends Fragment {


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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //giving me error cannot resolve method
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.music_marimba_chord);

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        ImageView share = (ImageView)view.findViewById(R.id.share);

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
                startActivity(Intent.createChooser(sharingIntent, "Share via"));

        ImageView send = (ImageView)view.findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(""));
                startActivity(intent);
            }
        });



        return view;
    }

    // set fragment to portrait
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
            Activity a = getActivity();
            if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }


}

If you want to use SoundPool , the following will play a different sound when click or select event are triggered on the fragment :

public abstract class MainFragment extends Fragment {

    private SoundPool soundPool;
    private HashMap<Integer, Integer> soundPoolMap;

    public void onCreate() {
        initSounds(getActivity().getApplicationContext());
    }

    public void initSounds(Context context) {
        soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 100);
        soundPoolMap = new HashMap(1);
        soundPoolMap.put(R.raw.music1, soundPool.load(context, R.raw.music1, 1));
        soundPoolMap.put(R.raw.music2, soundPool.load(context, R.raw.music2, 1));
    }

    public void playSound(int soundID) {

        float volume = 0.2f;

        // play sound with same right and left volume, with a priority of 1,
        // zero repeats (i.e play once), and a playback rate of 1f
        soundPool.play(soundPoolMap.get(soundID), volume, volume, 1, 0, 1f);
    }

    private void playSoundClick() {
        playSound(R.raw.music1);
    }

    private void playSoundSelect() {
        playSound(R.raw.music2);
    }

    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                playSoundClick();
            } else {
                playSoundSelect();
            }
        }
        return true;
    }
}

The sound is played here :

soundPool.play(soundPoolMap.get(soundID), volume, volume, 1, 0, 1f);

where you can set volume left & right and priority in case you want this sound to prevail over other if another one is being played in the same SoundPool

To integrate with your work :

public class HomeFragment extends MainFragment {


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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        super.onCreate();

        ImageView share = (ImageView)view.findViewById(R.id.share);

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                playSound(R.raw.music1);

                Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
                startActivity(Intent.createChooser(sharingIntent, "Share via"));

        ImageView send = (ImageView)view.findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                playSound(R.raw.music2);

                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(""));
                startActivity(intent);
            }
        });

        return view;
    }
}

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