我是一个新手,通过制作一个简单的游戏来学习android:
用户可以按下几个按钮
我在屏幕上显示一些问题,他必须按下其中一个按钮作为答案
当他按下按钮时,我播放声音。
3个错误答案,游戏结束。
简单对吧?
一切正常,我学到了很多,除了一个"#%#"%"#"异常,不断崩溃我的应用程序:(
这真的很奇怪,如果回答错误3次游戏就结束了,所以我运行这段代码:
soundPool.release();
this.finish();
将用户发送回最后一个活动,他们可以重新开始游戏。问题每3-5次就会出现。我得到一个力关闭,这是在logcat:http://imageshack.us/photo/my-images/90/91939698.png/
错误似乎在这里:
public void playSound(int sound) {
AudioManager mgr = (AudioManager)GameScreen.this.getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
/** The below line is line 117 that is crashing the program */
soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f);
}
请告诉我怎样才能解决这个恼人的"bug"。
谢谢!
瑞安
================================================================================
编辑:在onCreate我正在做这个:
new LoadMusicInBackground().execute();
和LoadMusicInBackground是这样的
/** Helper class to load all the music in the background. */
class LoadMusicInBackground extends AsyncTask<Void, String, Void>
{
@Override
protected Void doInBackground(Void... unused) {
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(A1, soundPool.load(GameScreen.this, R.raw.a, 1));
soundPoolMap.put(A3, soundPool.load(GameScreen.this, R.raw.b, 1));
soundPoolMap.put(A5, soundPool.load(GameScreen.this, R.raw.c_s, 1));
soundPoolMap.put(A6, soundPool.load(GameScreen.this, R.raw.d, 1));
soundPoolMap.put(A8, soundPool.load(GameScreen.this, R.raw.e, 1));
soundPoolMap.put(A10, soundPool.load(GameScreen.this, R.raw.f_s, 1));
soundPoolMap.put(A12, soundPool.load(GameScreen.this, R.raw.g_s, 1));
soundPoolMap.put(wrong, soundPool.load(GameScreen.this, R.raw.wrong2, 1));
publishProgress("");
Log.v("SOUNDPOOL",""+soundPoolMap);
return(null);
}
@Override
protected void onProgressUpdate(String... item)
{
//text1.setText(item[0]);
}
@Override
protected void onPostExecute(Void unused) {
//Toast .makeText(GameScreen.this, "Done!", Toast.LENGTH_SHORT).show();
}
}
…
编辑:public void release()
释放SoundPool资源。释放所有内存和本机SoundPool对象使用的资源。SoundPool不能再存在了使用时,引用应设置为null。
你不能重用soundPool对象一旦你调用释放,所以你需要创建一个新的实例。因此,执行以下操作以确保它不会被重新发布:
soundPool.release();
soundPool = null;
我会尝试记录soundPool和soundPoolMap,因为它看起来像其中一个是null。
也许作为重新启动游戏的一部分,这些值被清除?
对于一个新手来说你做得很好:-D
我认为这是导致你的问题的原因:
soundPool.release();
您可能会释放它并尝试下次重用它。参见release()文档....