2017-05-05 18 views
0

我在另一個類中從我的SoundManager類調用方法時遇到了一些麻煩。這是SoundManager類。在不同類中播放聲音類Android

公共類SoundManager類{

private SoundPool soundPool; 
public static final int maxSounds = 2; 
AudioManager audioManager; 
private int[] soundId; 
private Context context; //= mGame.getActivity().getApplicationContext(); 
Game mGame; 
public SoundManager(Game game) { 
    super(); 
    context = game.getActivity().getApplicationContext(); 
    //this.mGame = game; 

    soundPool = new SoundPool(maxSounds, AudioManager.STREAM_MUSIC, 0); 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
     soundPool = new SoundPool.Builder() 
       .setMaxStreams(maxSounds) 
       .build(); 
    } else { 
     soundPool = new SoundPool(maxSounds, AudioManager.STREAM_MUSIC, 0); 
    } 

    soundId = new int[16]; 

    soundId[0] = soundPool.load(context, R.raw.sound1, 1); 
    //soundId[1] = soundPool.load(context, R.raw.cardsound, 1); 
    soundId[2] = soundPool.load(context, R.raw.swoosh, 1); 
    soundId[3] = soundPool.load(context, R.raw.clicksound, 1); 
    soundId[4] = soundPool.load(context, R.raw.scifi, 1); 
    soundId[5] = soundPool.load(context, R.raw.phasebattle, 1); 
    soundId[6] = soundPool.load(context, R.raw.card_mr_electron, 1); 
    soundId[7] = soundPool.load(context, R.raw.card_james_watt, 1); 
    soundId[8] = soundPool.load(context, R.raw.card_marvin, 1); 
    soundId[9] = soundPool.load(context, R.raw.card_leonardo, 1); 
    soundId[10] = soundPool.load(context, R.raw.card_edmund, 1); 
    soundId[11] = soundPool.load(context, R.raw.card_terminator, 1); 
    soundId[12] = soundPool.load(context, R.raw.card_mr_robot, 1); 
    soundId[13] = soundPool.load(context, R.raw.card_labrat, 1); 
    soundId[14] = soundPool.load(context, R.raw.card_nerd, 1); 
    soundId[15] = soundPool.load(context, R.raw.card_angle, 1); 

    audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 
} 

public void playSound(int sound, float volume) { 
    soundPool.play(soundId[sound], volume, volume, 1, 0, 1f); 
} 

而這裏就是我想稱之爲第二類的一部分。當我去運行應用程序時,堆棧跟蹤將我恢復到SoundManager中用於初始化上下文的行,並指出.getActivity()無法在空對象引用上初始化。

公共類播放器{

private GameScreen mGameScreen; 

private Game mGame; 
SoundManager mSoundManager = new SoundManager(mGame); 

public Player(GameScreen gameScreen, GameEventHandler mGameEventHandler, Game game) { 
    super(); 

} 

回答

0

當初始化SoundManagerGame尚不存在。

試試這個:

public class Player { 

private GameScreen mGameScreen; 

    private Game mGame; 
    SoundManager mSoundManager; 

    public Player(GameScreen gameScreen, GameEventHandler mGameEventHandler, Game game) { 
      super(); 
      mSoundManager = new SoundManager(game) 

    } 
    . 
    . 
+0

你是一個絕對的生命的救星非常感謝你!!!! –

+0

:)高興地幫助。如果它適合你,請接受答案。 – rupps