How To Create Button To Control Background Sound.
I'm trying to add background music to my application. All I want is the sound should played on pressing the btnoptn Button and its text transitions into the 'music off'. The music
Solution 1:
This is a really simple example. I don't know how it works if you switch between Activities, i never really worked with the MediaPlayer class.
public class MainActivity extends Activity
{
private MediaPlayer mediaPlayer;
private Button musicButton;
private OnClickListener listener = new OnClickListener()
{
// a boolean value in the names Onclicklistener class.
// this will help us to know, if the music is playing or not.
boolean isPlaying = false;
@Override
public void onClick(View arg0)
{
if(isPlaying)
{
mediaPlayer.pause(); //stop the music
musicButton.setText("Start"); //change the buttons text
}
else
{
mediaPlayer.start(); //start the music
musicButton.setText("Stop"); //change the text
}
//changing the boolean value
isPlaying = !isPlaying;
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Creating the mediaplayer with a desired soundtrack.
mediaPlayer = MediaPlayer.create(this, R.raw.my_music);
//Getting the Button reference from the xml
musicButton = (Button) findViewById(R.id.music_button);
//Setting the listener
musicButton.setOnClickListener(listener);
}
}
Post a Comment for "How To Create Button To Control Background Sound."