Friday, February 10, 2012

How to create a SoundPool in android with the help of SFXManager?

Create the below class in android application..........

public class SFXManager {

private Context context;
private final int MAX_STREAMS = 10;

private SoundPool soundpool;
private float volume = 1;
AudioManager mAudioManager;

private TreeMap<String, Integer> nameToId = new TreeMap<String, Integer>();

public SFXManager(Context context) {
this.context = context;
soundpool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 100);
mAudioManager = (AudioManager) this.context.getSystemService(Context.AUDIO_SERVICE);
}

public void addSound(String soundname, String assetPath) {
try {
nameToId.put(soundname, soundpool.load(context.getResources().getAssets().openFd(assetPath), 100));
} catch (IOException e) {
Log.e("CanvasGame", "Could not open SoundFile" + assetPath);
}
}

public void play(String soundname) {
soundpool.play(nameToId.get(soundname), volume, volume, 1, 0, 1f);
}

public void play(String soundname, float rate) {
soundpool.play(nameToId.get(soundname), volume, volume, 1, 0, rate);
}

public void playLoopedSound(String soundname) {
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume/ mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
soundpool.play(nameToId.get(soundname), streamVolume, streamVolume, 1,-1, 1f);

}
public void stopSounds() {
soundpool.pause(1);
}
public void release() {
soundpool.release();
soundpool = null;
}
public void setVolumeOf(float v) {
volume = v;
}
public float getVolume() {
return volume;
}
// http://code.google.com/p/candroidengine/source/browse/trunk/src/at/
// bartinger/candroid/sound/SFXManager.java
// good help for replaying the splash sound again and again
}

and just call the below methods for functioning.......create the sounds folder in assets folder and place the ogg file in it...

SFXManager sound = new SFXManager(getApplicationContext());
sound.addSound("splash", "sounds/splashsound.ogg");

for playing sound use.....
sound.play("splash");
for plaing in loop......
sound.playLoopedSound("splash");
for setting the volume......
sound.setVolumeOf(50);
for stop playing and releasing sound...
sound.stopSounds();
sound.release();






No comments:

Post a Comment