Tuesday 17 September 2013

Are you playing with sounds in your app?

Here is the playground for u.....




If you developing an app and struggling with managing sounds here is the solution;

SoundPoolDemo
Some code snippet :

public class LauncherActivity extends Activity implements OnTouchListener {
private SoundPool soundPool;
final static int MAX_STREAMS = 5;
private boolean isLoaded = false;
private int soundOneID;
private int soundTwoID;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
((RelativeLayout) findViewById(R.id.bg)).setOnTouchListener(this);
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {

@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
Log.d("TESTING", "sampleId :" + sampleId + " status :" + status);
isLoaded = true;
}

});

soundOneID = soundPool.load(this, R.raw.shoot_1, 1);
soundTwoID = soundPool.load(this, R.raw.shoot_2, 1);

Log.d("TESTING", "soundOneID :" + soundOneID);
Log.d("TESTING", "soundTwoID :" + soundTwoID);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.launcher, menu);
return true;
}

@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
Log.d("TESTING", actualVolume + ":  actualVolume");
Log.d("TESTING", maxVolume + ":  maxVolume");
Log.d("TESTING", volume + ": volume");
if (isLoaded) {
soundPool.play(soundOneID, volume, volume, 1, 0, 1f);
}
}
return false;
}

@Override
protected void onStop() {
if (soundPool != null) {
// To release all the resources of soundPool
soundPool.release();
}
super.onStop();
}
}

If you have any query, ask me.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Sound pool sounds a good alternative when playing sounds that are already available to us.
    But for playing sounds that are just bytes of sound data that don't have the particular file header attached to it can't be played using the sound pool.

    ReplyDelete