使用MediaPlayer for Android Studio

时间:2018-10-03 06:25:47

标签: android-mediaplayer

进入片段页面后,我想在后台自动播放音乐。我相信注释掉的部分是如何实现的,但是我可能输入的第一个参数不正确?

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);
}

还是我在错误的位置进行编码,它应该是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();

2 个答案:

答案 0 :(得分:0)

使用getActivity()。它为Media Player提供所需的上下文。尝试使用以下代码:

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

您的片段代码应如下所示:

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);
}

尝试一下。希望对您有帮助!

答案 1 :(得分:0)

您可以只使用getActivityfragment类中获取活动的上下文。

如下。

public class AlphabetFragment extends Fragment {

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

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

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