java - 单独的类来播放声音

标签 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));”

您能澄清一下问题所在吗?

最佳答案

许多问题:

  • 您的类(class)不应该是一个 Activity ,而是一个常规类(class)。

  • Activity 不应具有显式构造函数。

  • onCreate() 之前,您无法将 Activity 用作上下文。作为 Context 传递给 load()this 指针将导致平台 getBaseContext() 中出现 NPE .

修复它:

  • 使该类不扩展 Activity

  • 使用 myContext 参数作为 Context 而不是 this

关于java - 单独的类来播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20033178/

相关文章:

Android 使用 OnClick 从 SD 卡中删除图像

android - 检测 Android Cordova webview 何时完成加载

android - moveCamera 没有更新到我在 Google map Android 上的当前位置?

java - 什么是 "allocation pools for temporary objects"?

java - 为什么 HtmlUnit 代码与 Chrome 代码不匹配?

c++ - 需要帮助理解未在范围内声明的对象

java - MyInternalFrame 无法解析为类型

java - 如何解决 ClassNotFoundException?

java - Okhttp3 - 接受所有证书并使用 certificatePinner

java - 如何提取两个 "/"字符之间的字符串