getContext() 在处理 SoundPool 时在片段中(想要播放数据库中的声音文件)



我的用户界面应用程序有一个音量,当用户按下时播放声音文件。这是保存卷的片段。 我贡献了一个 SoundManager 类来执行以下功能:构造、加载和播放 soundpool 对象

声音管理器.java

public class SoundManager {
private SoundManager soundManager;
SoundPool soundPool;
int CLICK_SOUND;

public SoundManager(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
soundPool = (new SoundPool.Builder()).setMaxStreams(1).build();
}else{
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 5);
}
}
public void loadSound(Context context, int resID){
CLICK_SOUND = soundPool.load(context, resID, 1);
// CLICK_SOUND1 = soundPool.load(context, R.raw.vegetable, 1);
// load other sound if you like
}
public void playClickSound(){
soundPool.play(CLICK_SOUND, 1.0F, 1.0F, 0, 0, 1.0F);
}
}

然后,在 Fragment.java. Inside@override onCreateView中,我使用getActivity().getApplicationContext()来获取此片段的上下文。

如果我把soundManager.loadSound(context,resID)放在getActivity().getApplicationContext()下面 当然,当用户按下音量按钮时,声音正在播放。 但是,当我soundManager.loadSound(context,resID)放入OnClick()功能时,声音无法播放。 我该如何修复它

片段.java

> .....inside onCreatView(...)
context=getActivity().getApplicationContext();
final SoundManager soundManager=new SoundManager();
//soundManager.loadSound(context,resID);// Okay, Sound is run...
btnVolume.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String action="handlerSoundVolume";
//LoadSound in here is not active...????
soundManager.loadSound(context,resID);
soundManager.playClickSound();
mainRoundMode4.itemClicked(action,"");
}
});

context=getActivity().getApplicationContext()更改为context = getContext();

最新更新