所以,我正在制作一个带有滚动选项卡+滑动导航的应用程序。在每个选项卡的页面中,我都想播放不同的音频文件。
下面是我的片段的OnCreateView,包含媒体播放器FileDescriptor的初始化,并在assets文件夹中播放一个名为.mp3的音频文件。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
///Playing sound from here on
AssetFileDescriptor fda;
MediaPlayer amp = new MediaPlayer();
try {
fda = getAssets().openFd("a.mp3");//// GIVES ERROR !
amp.reset();
amp.setDataSource(fda.getFileDescriptor());
amp.prepare();
amp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return rootView;
}
}
GetAssets()方法给出如下错误:
Cannot make a static reference to the non-static method getAssets() from the type ContextWrapper
尽管从声明FileDescriptor到最终Catch语句的这段代码在正常的空白活动的OnCreate中非常有效。它在这里不起作用。
有什么解决方案吗?
我可以以某种方式使getAssets()方法静态吗?
有其他方法可以从片段中访问音频文件吗?
(记住,我的目标是在每个不同选项卡的屏幕上播放不同的音频文件。我稍后会添加更多的音频文件,只是试着至少让这个先工作。)
请帮助:)
谢谢!
您需要使用Context对象,因此在本例中可以使用:
rootView.getContext().getAssets().openFd("a.mp3");
也就是说,我建议稍后在视图层次结构实例化后,在onActivityCreated
或onStart
中的片段生命周期中移动此代码。将此代码放在onCreateView
中可能会延迟/减慢向用户显示UI的速度。
通过这些稍后的生命周期方法,您可以安全地调用:getResources().getAssets().openFd("a.mp3");
只需将getAssets()替换为context.getAssets(:)
您可以在实用程序类中指定以下2个方法。他们为您返回AssetManager
:
public static AssetManager getMyAssets(Context context)
{
return context.getResources().getAssets();
}
public static AssetManager getMyAssets(View view)
{
return view.getContext().getResources().getAssets();
}
现在你可以这样使用它们:
fda = myUtil.getMyAssets(rootView).openFd("a.mp3");
或
fda = myUtil.getMyAssets(rootView.getContext()).openFd("a.mp3");