tags:

views:

46

answers:

1

I have a program with a function copied below it plays a sound upon clicking a button. If you click the button 10 times 10 different media players play the same sound that is the way i want it but how can i assign a button to stop all 10 media players at a time like a "STOP ALL BUTTON"

public void onClick(View v){
 int resId = 0;
 int stopped = 0;
 switch (v.getId()){
 case R.id.Wail:
  resId = R.raw.fedsigwail;
  break;
 case R.id.Yelp:
  resId = R.raw.fedsigyelp;
  break;
 case R.id.HiLow:
  resId = R.raw.hilow;     
  break;
 case R.id.FederalQ:
  resId = R.raw.federalq;
  break;
 case R.id.Horn:
  resId = R.raw.fedsignhorn;
  break;
 case R.id.STOPALL:
  mp.stop();
  mp.release();
  stopped = 1;
  break;
 }

 if (stopped != 1){
 mp = MediaPlayer.create(this, resId);
 mp.start();
 }


}

The code above only stops the last instance of mp.

Any Input would be appreciated

A: 

mp.stop(); only stops one instance of a media player, since mp can only be one mediaplayer instance. If mp is one of your media players, where are the other ones? You mentioned you have

10 different media players

so I would expect something like mp1, mp2, mp3, ..., mp10. But right now it seems you actually only using one media player instance, or at least stopping it.

With each call of

mp = MediaPlayer.create(this, resId)

you lose the reference to the previous created media player, since you 'override' it with a newly created instance. You need to keep a reference to all your created media players, i.e. via an ArrayList or HashMap or similar.

Mathias Lin
So go with an Array of Media Player Objectsie: MPArray[i] = MediaPlayer.Create(this, resId);i++then to kill all soundsdo a length on MPArraythen a for loop to go from 0 index to length index of the array can call stop on each for example MPArray[2].stop()?Is that what you suggesting i do? or and i way overthinking it
i did it like this and got a force close i dont know where i went wrong.public class Hello extends Activity implements OnClickListener, OnLongClickListener { int resId = 0; int status = 0; int mpindex = 0; private MediaPlayer mpArray[] = new MediaPlayer[999]; public void onClick(View v){ int resId = 0; int stopped = 0;*** REMOVED SWITCH FUNCTION TO ASSIGN RESID DUE TO CHARACTER LIMIT. ***// Create MediaPlayer instances mpArray[mpindex].create(this, resId); mpArray[mpindex].start(); }When i click to play sound get force close
Force close: check the logfile (adb shell logcat) or logcat in Eclipse. btw: please add the code to your initial quesions, there it gets formatted and easier to read. In a comment it's hard to read.
Mathias Lin
Shouldn't the line to create the media player be like this: mpArray[mpindex] = MediaPlayer.create(this, resId); otherwise you're not assigning anything to mpArray[mpindex]
Mathias Lin
Fixed it thanks
great. btw: if the answer was helpful, please accept by clicking the green checkmark. thanks
Mathias Lin