Search code examples
android-mediaplayer

Using MediaPlayer for Android Studio


I would like to automatically play music in the background when I enter this Fragment page. I believe the commented out section is how you implement it, but I might be typing the first parameter incorrectly?

public class AlphabetFragment extends Fragment {

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

    //MediaPlayer mysong;
    //mysong = MediaPlayer.create(AlphabetFragment.this, R.raw.alphabetlist);
    //mysong.start();

    return inflater.inflate(R.layout.fragment_alphabet, container, false);
}

Or am I coding this in the wrong spot, should it be part of the MainActivity.java?

case R.id.nav_alphabet:

getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AlphabetFragment()).commit();
                    //mysong = MediaPlayer.create(AlphabetFragment., R.raw.alphabetlistm4a);
                    //mysong.start();

Solution

  • Use getActivity(). It gives the Media Player the context it needs. Try to use this code:

    MediaPlayer mp = MediaPlayer.create( getActivity() , R.raw.alphabetlist );
    

    Your fragment code should look like this:

    MediaPlayer mp; 
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    
        mp=MediaPlayer.create(getActivity(), R.raw.alphabetlist); 
        mp.start():  
    
        return inflater.inflate(R.layout.fragment_alphabet, container, false);
    }
    

    Try this. Hope it helps!