代码中是否有错误?
它适用于我的主要活动和我的片段。但是如果我在声音类中使用方法(loadSound),则getAssets()不起作用。
请帮帮我,有什么想法吗? 谢谢!
这是我的片段代码:
public class CarnivoreFragment extends Fragment {
private int mCowSound;
private View view;
private ImageButton mCowImageButton;
public CarnivoreFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_carnivore, container, false);
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Sound.createOldSoundPool();
} else {
Sound.createNewSoundPool();
}
mCowSound = Sound.loadSound("cow.wav");
mCowImageButton = (ImageButton) view.findViewById(R.id.imageButtonCow);
mCowImageButton.setOnClickListener(onClickListener);
return view;
}
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButtonCow:
Sound.playSound(mCowSound);
Toast.makeText(view.getContext(), "Cow", Toast.LENGTH_SHORT).show();
break;
}
}
};
}
和我的“声音”课程:
public class Sound {
private static SoundPool mSoundPool;
private static AssetManager mAssetManager;
private static int mStreamID;
private static Context context;
public Sound(Context context) {
this.context = context;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void createNewSoundPool() {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
mSoundPool = new SoundPool.Builder()
.setAudioAttributes(attributes)
.build();
}
@SuppressWarnings("deprecation")
public static void createOldSoundPool() {
mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
}
public static int playSound(int sound) {
if (sound > 0) {
mStreamID = mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
return mStreamID;
}
public static int loadSound(String fileName) {
mAssetManager = context.getAssets();
AssetFileDescriptor afd;
try {
afd = mAssetManager.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Не могу загрузить файл " + fileName,
Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
}
}
答案 0 :(得分:0)
看起来您可能永远不会在Sound类中设置上下文,因为所有调用似乎都是通过静态方法调用的。你有一个类在构造函数中设置上下文,但似乎没有调用构造函数。