4

I made a SoundManager class that uses SoundPool functions in order to loop a specific sound, however I can't figure out why it isn't playing a sound.

public class SoundManager {
private  SoundPool mSoundPool; 
private  HashMap<Integer, Integer> mSoundPoolMap; 
private  AudioManager  mAudioManager;
private  Context mContext;

public SoundManager()
{

}

public void initSounds(Context theContext) { 
     mContext = theContext;
     mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0); 
     mSoundPoolMap = new HashMap<Integer, Integer>(); 
     mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);         
} 

public void addSound(int Index, int SoundID) {
    mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));
}

public void playSound(int index) { 
     int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
     mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f); 
}

public void playLoopedSound(int index) { 
     int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
     mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f); 
}

}

This class is being called from my Activity via:

private SoundManager mSoundManager;
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.sound);
mSoundManager.playSound(1);
Chris Fogarty
  • 61
  • 1
  • 4

2 Answers2

2

Apparently it doesn't work onCreate for my activity but calling it when an event happen (Intents / Keypress) it seems to work

Chris Fogarty
  • 61
  • 1
  • 4
  • It does work with onCreate. I tested it out, I think you may have to wait until the sound loads. That's according to https://stackoverflow.com/questions/55200787/soundpool-not-playing-sound-while-mediaplayer-does Try this and see if it works. – Anirudh Ganesh Aug 10 '20 at 14:23
1

I had this problem and finally solved it by running on an emulator that supported audio!!

Can't believe it was that simple!

Window > AVD Manager > Edit your AVD (I created a new one to be on the safe side cause I was running from snapshot) > Hardware > New > Audio Playback Support