Playing multiple SoundPool at the same time - android

I have a activity that i'm using 12 button with different sound at them. Buttons should be play at the same time if user click both of them at once.
When i use MediaPlayer i couldn't manage to do this , then i learned about SoundPool and everything was fine.But with 12 different sounds I had to write so many row and i don't think that's the right way to do this.
Is this the right way to do this , when i write this for 12 sound it became to long ?
SoundPool sp1,sp2,sp3;
int id1,id2,id3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.piano);
sp1 = new SoundPool(1, AudioManager.STREAM_MUSIC,1);
sp2 = new SoundPool(1, AudioManager.STREAM_MUSIC,1);
sp3 = new SoundPool(1, AudioManager.STREAM_MUSIC,1);
id1 = sp1.load(this,R.raw.p1,1);
id2 = sp2.load(this,R.raw.p2,1);
id3 = sp3.load(this,R.raw.p3,1);
}
public void p1Click(View v)
{
sp1.play(id1,1,1,1,0,1);
}
public void p2Click(View v)
{
sp2.play(id1,1,1,1,0,1);
}
public void p3Click(View v)
{
sp3.play(id1,1,1,1,0,1);
}

You only need one SoundPool (sp1):
sp1 = new SoundPool(12, AudioManager.STREAM_MUSIC,1);
id1 = sp1.load(this,R.raw.p1,1);
id2 = sp1.load(this,R.raw.p2,1);
...
sp1.play(id1,1,1,1,0,1);
sp1.play(id2,1,1,1,0,1);
...
(1) Note the 12 means you can play 12 sounds concurrently.
(2) Note keep track of your active sounds, it will be useful later. (sp1.play returns an integer):
int streamID = sp1.play(id1,1,1,1,0,1);

Related

Android button soundboard

I'm trying to make a soundboard app, but I'm running into a problem with handling the sound files. More specifically I do not know how to get it so when a button is pressed it plays a corresponding sound back.
I've tried using this way
Play sound on button click android
I tried implementing a media player for each sound file and button but the app crashes on start up.
I have 10 buttons with 10 corresponding sound files that are located in the raw file in src/res/raw/
Any idea on how to make it work?
//this is a breaking bad soundboard app, so please excuse the language. Sorry if you find it offensive
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
whatup = (Button)this.findViewById(R.id.button);
haveatit = (Button)this.findViewById(R.id.button2);
hello = (Button)this.findViewById(R.id.button3);
whining = (Button)this.findViewById(R.id.button7);
money = (Button)this.findViewById(R.id.button4);
yeah= (Button)this.findViewById(R.id.button8);
miserable = (Button)this.findViewById(R.id.button5);
mother = (Button)this.findViewById(R.id.button9);
gatorade = (Button)this.findViewById(R.id.button6);
science = (Button)this.findViewById(R.id.button10);
whatup.setOnClickListener(this);
haveatit.setOnClickListener(this);
hello.setOnClickListener(this);
whining.setOnClickListener(this);
money.setOnClickListener(this);
yeah.setOnClickListener(this);
miserable.setOnClickListener(this);
mother.setOnClickListener(this);
gatorade.setOnClickListener(this);
science.setOnClickListener(this);
WhatUp = MediaPlayer.create(MainActivity.this, R.raw.whatupb);
HaveAtIt = MediaPlayer.create(MainActivity.this, R.raw.haveatit);
Hello = MediaPlayer.create(MainActivity.this, R.raw.hello);
Whining = MediaPlayer.create(MainActivity.this, R.raw.stopwhining);
Money = MediaPlayer.create(MainActivity.this, R.raw.wheresmymoney);
Yeah = MediaPlayer.create(MainActivity.this, R.raw.yeahb);
Miserable = MediaPlayer.create(MainActivity.this, R.raw.miserableb);
Mother = MediaPlayer.create(MainActivity.this, R.raw.motherofgod);
Gatorade = MediaPlayer.create(MainActivity.this, R.raw.gatorade);
Science = MediaPlayer.create(MainActivity.this, R.raw.yeahscience);
}
this is for handling when the button is pressed. Obviously there needs to be more, but I was just testing 1 button and it crashes when I try starting it.
#Override
public void onClick(View view) {
if(view==whatup)
{
WhatUp.start();
}
}
Log Cat Errors:
http://imgur.com/ZWYsLl7
I assume your sounds might be sound_1, sound_2, sound_3, etc. and your buttons are button_1, button_2 and so on..
You should create a loop to get the ids in onCreate method:
for (int i = 0; i < 10; i++) {
// get the id for buttons
int btnId = getResources().getIdentifier("button_"+i, "id", getPackageName());
// get the res for sounds
int rawId = getResources().getIdentifier("sound_"+i, "raw", getPackageName());
// set a click listener to all your buttons
button[i] = (Button) findViewById(id);
button[i].setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// create the media player with the raw id
mp = MediaPlayer.create(MainActivity.this, rawId);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// avoid NullPointerException see the links below
mp.release();
}
});
// play the sound
mp.start();
}
});
}
Read the topic reference: Using MediaPlayer. You could also get identifer with the context: How to dynamically generate the raw resource identifier in android? and this might help you for explanation of release() method: Play sound on button click - Null pointer exception and read the Releasing the MediaPlayer part from Using MediaPlayer. I'm not sure but it should do the trick..
Good luck.
UPDATE
Change this check if(view==whatup) to if(view.getId() == R.id.button).
In onClick method you need to check the id regarding the view, with getId() method.

Playing short .wav files - Android

I would like to play sound after touching the button. MediaPlayer works fine, but I read somewhere that this library is for long .wav (like music).
Is there any better way to play short .wav(2-3 sec.)?
The SoundPool is the correct class for this. The below code is an example of how to use it. It is also the code I use in several apps of mine to manage the sounds. You can have as may sounds as you like (or as memory permits).
public class SoundPoolPlayer {
private SoundPool mShortPlayer= null;
private HashMap mSounds = new HashMap();
public SoundPoolPlayer(Context pContext)
{
// setup Soundpool
this.mShortPlayer = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSounds.put(R.raw.<sound_1_name>, this.mShortPlayer.load(pContext, R.raw.<sound_1_name>, 1));
mSounds.put(R.raw.<sound_2_name>, this.mShortPlayer.load(pContext, R.raw.<sound_2_name>, 1));
}
public void playShortResource(int piResource) {
int iSoundId = (Integer) mSounds.get(piResource);
this.mShortPlayer.play(iSoundId, 0.99f, 0.99f, 0, 0, 1);
}
// Cleanup
public void release() {
// Cleanup
this.mShortPlayer.release();
this.mShortPlayer = null;
}
}
You would use this by calling:
SoundPoolPlayer sound = new SoundPoolPlayer(this);
in your Activity's onCreate() (or anytime after it). After that, to play a sound simple call:
sound.playShortResource(R.raw.<sound_name>);
Finally, once you're done with the sounds, call:
sound.release();
to free up resources.

MediaPlayer how to stop multiple sounds from playback

i have a button that plays a sound.
When i push the button multiple times, it plays the sound multiple times.
This is oke, i want this.
But when i click the stop button it must stop all sounds currently playing.
I used:
while (mediaPlayer.isPlaying()){mediaPlayer.stop();}
but it is not working, the sounds keep on playing. Can someone help me?
Here is my full code:
public class HelloSoundboard extends Activity {
MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button item1 = (Button)findViewById(R.id.item1);
item1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mediaPlayer = MediaPlayer.create(getBaseContext(), R.raw.atyourservice);
mediaPlayer.start();
}
});
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
while (mediaPlayer.isPlaying()){mediaPlayer.stop();}
// mediaPlayer.stop();
}
});
}
}
SoundPool is a much better alternative for this purpose. I would caution strongly against instantiating multiple MediaPlayer instances as most systems do not have the resources to generate many parallel active instances. You wil find on many device that hitting the button upwards of 5 times will cause a memory based crash.
As far as stopping all active streams, there is not baked-in function for this, but it's easy to accomplish in a manner to similar to your existing code. As a side note, there is an autoPause() method, which halts all streams, but it doesn't truly end their playback (as the method name insinuates). Here is a simple example to manage your audio streams:
//SoundPool initialization somewhere
SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
//Load your sound effect into the pool
int soundId = pool.load(...); //There are several versions of this, pick which fits your sound
List<Integer> streams = new ArrayList<Integer>();
Button item1 = (Button)findViewById(R.id.item1);
item1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int streamId = pool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
streams.add(streamId);
}
});
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Integer stream : streams) {
pool.stop(stream);
}
streams.clear();
}
});
It is much more memory efficient to manage a list of streamID values than MediaPlayer instances, and your users will thank you. Also, note that it is safe to call SoundPool.stop() even if the streamID is no longer valid, so you don't need to check for existing playback.
HTH
I'm not sure about this, but I think is better if you use a SoundPool.
"SoundPool is designed for short clips which can be kept in memory decompressed for quick access, this is best suited for sound effects in apps or games".
"MediaPlayer is designed for longer sound files or streams, this is best suited for music files or larger files".
You can use a list of MediaPlayers:
List<MediaPlayer> mps = new ArrayList<MediaPlayer>();
Button item1 = (Button)findViewById(R.id.item1);
item1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.atyourservice);
mp.start();
mps.add(mp);
}
});
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (int i = mps.size() - 1; i >= 0; --i) { //changed ++i to --i
if (mps.get(i).isPlaying()) {
mps.get(i).stop();
}
mps.remove(i);
}
}
});

Playing multiple sounds using SoundManager

If I play a single sound, it runs fine.
Adding a second sound causes it to crash.
Anyone know what is causing the problem?
private SoundManager mSoundManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sos);
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1,R.raw.dit);
mSoundManager.addSound(1,R.raw.dah);
Button SoundButton = (Button)findViewById(R.id.SoundButton);
SoundButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.playSound(1);
mSoundManager.playSound(2);
}
});
}
mSoundManager.addSound(1,R.raw.dit);
mSoundManager.addSound(1,R.raw.dah);
You need to change the second line to:
mSoundManager.addSound(2,R.raw.dah);
In order to play multiple sounds at once, first you need to let the SoundPool know that. In the declaration of SoundPool notice that I specified 20 streams. I have many guns and bad guys making noise in my game, and each has a very short sound loop, < 3000ms. Notice when I add a sound below I keep track of the specified index in a vector called, "mAvailibleSounds", this way my game can try and play sounds for items that dont exist and carry on without crashing. Each Index in this case corresponds to a sprite id. Just so you understand how I map particular sounds to specific sprites.
Next we queue up sounds, with playSound(). Each time this happens a soundId is dropped into a stack, which I then pop whenever my timeout occurs. This allows me to kill a stream after it has played, and reuse it again. I choose 20 streams because my game is very noisy. After that the sounds get washed out, so each application will require a magic number.
I found this source here, and added the runnable & kill queue myself.
private SoundPool mSoundPool;
private HashMap<Integer, Integer> mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;
private Vector<Integer> mAvailibleSounds = new Vector<Integer>();
private Vector<Integer> mKillSoundQueue = new Vector<Integer>();
private Handler mHandler = new Handler();
public SoundManager(){}
public void initSounds(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
public void addSound(int Index, int SoundID)
{
mAvailibleSounds.add(Index);
mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));
}
public void playSound(int index) {
// dont have a sound for this obj, return.
if(mAvailibleSounds.contains(index)){
int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int soundId = mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
mKillSoundQueue.add(soundId);
// schedule the current sound to stop after set milliseconds
mHandler.postDelayed(new Runnable() {
public void run() {
if(!mKillSoundQueue.isEmpty()){
mSoundPool.stop(mKillSoundQueue.firstElement());
}
}
}, 3000);
}
}

Android: Playing an audio clip onClick

How do I set up an audiofile to play when a user touches an image.
Where should I store the audio file and what code should I use to actually play the file?
I don't want to bring up the MediaPlayer interface or anything like that.
I was thinking of doing it like this:
foo = (ImageView)this.findViewById(R.id.foo);
foo.setOnClickListener(this);
public void onClick(View v) {
if (foo.isTouched()) {
playAudioFile();
}
}
Thanks
This won't create a bring up the MediaPlayer interface... it will just play the sound you want.
Button boton = (Button) findViewById(R.id.boton);
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(TestSonido.this, R.raw.slayer);
mp.start();
}
});
In this case, R.raw.slayer represents an audio file called slayer.mp3 that is stored in the res/raw/ folder and once you click the button the droid will rock you...
You can also achieve the same using SoundPool.
MediaPlayer first loads the whole sound data in memory then play, so it produces some lag when we switch among sounds frequently.
SoundPool is a better option with small size sound file and produces better result with .ogg media file.
SoundPool pl = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
// 5 indicates the maximum number of simultaneous streams for this SoundPool object
pl.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// The onLoadComplet method is called when a sound has completed loading.
soundPool.play(sampleId, 1f, 1f, 0, 0, 1);
// second and third parameters indicates left and right value (range = 0.0 to 1.0)
}
});
Button btn = findViewById(R.id.boton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sound = pl.load(this, R.raw.sound_01, 0);
}
});
public void aud_play(View view) {
if (!mp.isPlaying()) { //If media player is not playing it.
mp = MediaPlayer.create(this, R.raw.audio_name);
mp.start();
} else {// Toast of Already playing ...
}
}

Categories

Resources