单独的课程播放声音

时间:2013-11-17 16:29:02

标签: java android class soundpool

我做错了什么?

我创建了一个名为“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));”

你能澄清一下是什么问题吗?

1 个答案:

答案 0 :(得分:2)

许多问题:

  • 您的课程不应该是活动,而应是普通课程。

  • 活动不应该有明确的构造函数。

  • Context之前,您无法将活动用作onCreate()。您作为this传递给Context的{​​{1}}指针将导致平台load()中的NPE。

修复它:

  • 让课程不延伸getBaseContext()

  • Activity参数设为myContext,而不是Context

相关问题