• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Help With Playing Sounds On Android App

AndroidMan1

Member
Hello All,

I'm not sure if this is the right place to post this but here it is anyway,

I am creating an app where one part is 2 buttons, each button plays a looped sound when clicked. They only play the sound when the 'start' button is 'on'
What i have been stuggling with today, is to create a way to stop the looped sounds from playing when a 'off' button is pressed. I have managed to create this button and it works but after stopping and starting the sound again twice the looped sound doesn't stop and goes on forever. Or goes on forever if i click on the sound buttons 3 times and try to stop them.

Here is the main bits of the code i have use:



//create soundpool
SoundPool sp;

//Create Buttons
Button start, one, two;
//Create Intergers
int starton;
int SoundOne=0;
int SoundTwo=0;


public void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);
setContentView(R.layout.sounds);


sp= new SoundPool(1, AudioManager.STREAM_MUSIC, 0);

//Sets SoundOne as 'testnew' (a .ogg file)
SoundOne = sp.load(this, R.raw.testnew, 1);

//Sets SoundOne as 'testnew' (a .ogg file)
SoundTwo = sp.load(this, R.raw.testnew1, 1);

//sets up buttons to there id's
start = (Button) findViewById(R.id.startbutton);
one= (Button) findViewById(R.id.Button1);
two= (Button) findViewById(R.id.Button2);


//start button
start.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//if the start button has not been clicked yet set starton to =1
if (starton==0)
{
starton = 1;
sp.stop(onehz);
sp.stop(twohz);
}

//if the start button has been clicked before
//(i.e. starton==1) set starton =0
else
{
starton = 0;
sp.stop(onehz);
sp.stop(twohz);
}
}
});

//first sound button
one.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//if the on button has been pressed
if(starton==1)
{
//'-1' is the infinity loop
sp.play(onehz, 1, 1, 0, -1, 1);
}
}
});

//second sound button
two.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(starton==1)
{
sp.play(twohz, 1, 1, 0, -1, 1);
}


}
});
 
Back
Top Bottom