我做错了什么?
我创建了一个单独的类,名为“SoundClass”:
public class SoundClass extends Activity {
private SoundPool soundPool;
private int soundID;
private HashMap<Integer, Integer> soundsMap;
public int SoundYeah = 1;
public int SoundZwart = 2;
public int SoundBruin = 3;
public int SoundBlauw = 4;
public int SoundGroen = 5;
public int SoundGeel = 6;
public int SoundOranje = 7;
public int SoundRose = 8;
public int SoundWit = 9;
public int SoundPaars = 10;
public int SoundRood = 11;
public int SoundWrong = 12;
SoundClass(Context myContext){
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
soundsMap = new HashMap<Integer, Integer>();
soundsMap.put(SoundYeah, soundPool.load(this, R.raw.yeah, 1));
soundsMap.put(SoundZwart, soundPool.load(this, R.raw.c00, 1));
soundsMap.put(SoundBruin, soundPool.load(this, R.raw.c01, 1));
soundsMap.put(SoundBlauw, soundPool.load(this, R.raw.c02, 1));
soundsMap.put(SoundGroen, soundPool.load(this, R.raw.c03, 1));
soundsMap.put(SoundGeel, soundPool.load(this, R.raw.c04, 1));
soundsMap.put(SoundOranje, soundPool.load(this, R.raw.c05, 1));
soundsMap.put(SoundRose, soundPool.load(this, R.raw.c06, 1));
soundsMap.put(SoundWit, soundPool.load(this, R.raw.c07, 1));
soundsMap.put(SoundPaars, soundPool.load(this, R.raw.c08, 1));
soundsMap.put(SoundRood, soundPool.load(this, R.raw.c09, 1));
soundsMap.put(SoundWrong, soundPool.load(this, R.raw.wrong, 1));
}
public void playSound(int sound, float fSpeed) {
AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr
.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
soundPool.play(soundsMap.get(sound), volume, volume, 1, 0, fSpeed);
}
}
我想从我的 MainActivity 类中调用它,所以我使用:
SoundClass mSC = new SoundClass(this);
mSC.playSound(mSC.SoundBlauw, 1.0f);
但它出现错误(NPE 在线“soundsMap.put(SoundYeah, soundPool.load(this, R.raw.yeah, 1));”
您能澄清一下问题所在吗?
最佳答案
许多问题:
您的类(class)不应该是一个 Activity ,而是一个常规类(class)。
Activity 不应具有显式构造函数。
在
onCreate()
之前,您无法将 Activity 用作上下文
。作为Context
传递给load()
的this
指针将导致平台getBaseContext()
中出现 NPE .
修复它:
使该类不扩展
Activity
。使用
myContext
参数作为Context
而不是this
。
关于java - 单独的类来播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20033178/