androidandroid-fragmentsmplayer

mPlayer in fragment


Hello i had some truble for add a MdiaPlayer in my fragment but i thnik now it will wirk i need 1 lats thing its because my code :private MediaPlayer mPlayer = null; is "null" and i dont now what i need to put in the () of this line mPlayer = new MediaPlayer(); if someone can help me thanks a lot.

public class thekairi78 extends Fragment implements OnClickListener{

    View v;
    Button france2;
    private MediaPlayer mPlayer = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v  = inflater.inflate(R.layout.thekairi78, container, false);

        france2 = (Button) v.findViewById(R.id.france2);
        france2.setOnClickListener(this);

        mPlayer = new MediaPlayer();


        return v;
        }





    private void playSound(int resId){
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();

        }
        mPlayer = MediaPlayer.create(getActivity(), resId);
        mPlayer.start();
    }

    @Override
    public void onPause() {
        if(mPlayer != null && mPlayer.isPlaying()){
            mPlayer.pause();
        }
        super.onPause();

    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.france2:
                playSound(R.raw.france1);
                break;



        }

    }
}

Solution

  • change this line from

    mPlayer=new MediaPlayer()

    to

    mPlayer = MediaPlayer.create(getActivity(), R.raw.sample_song);