ali
ali

Reputation: 11

Play sound in a fragment

I want to press an image button and it should play an mp3 file in raw.

Here is my code and error in it -

public class Fragment_food_apple extends Fragment{

    MediaPlayer MediaPlayer;
    ImageButton btn;
    public Fragment_food_apple() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final MediaPlayer mp = MediaPlayer.create (this, R.raw.apple);
        //////problem is in up line and it is under this,
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mp.start();
            }
        });

    };

Upvotes: 1

Views: 1707

Answers (2)

Zeo
Zeo

Reputation: 109

I'm not sure if I missed something, but here you go. If you get any error, just let me know.

MediaPlayer mp;
ImageButton btn;
public Fragment_food_apple() {
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Inflate
    View view = inflater.inflate(R.layout.fragment_timer, container, false);

    //Find media player
    mp = MediaPlayer.create (getContext(), R.raw.apple);

    //Find your button
    btn = (Button) view.findViewById(R.id.YOUR_BUTTON);       

    btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        mp.start();
    }
});


};

Upvotes: 1

Markaos
Markaos

Reputation: 659

Method MediaPlayer.onCreate() requires an object of class Context as its first parameter, you are passing Fragment (which doesn't subclass Context) to it.

Use getActivity().getApplicationContext() instead.

Hope this helps you, comment if you have any questions.

Upvotes: 1

Related Questions