Reputation: 53
I know how to start the music file, but I don't know how to stop it. Here's my main activity:
public void button1 (View v){
Intent i = new Intent(MainActivity.this, CallActivity.class);
startActivity(i);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.music);
mp.setLooping(true);
mp.start();
}
Upvotes: 0
Views: 128
Reputation: 1612
You need to make your xml file with two buttons and set the button ID as ,playButton and stopButton
now use the below code..
public class MediaPlayerExample extends Activity implements OnClickListener {
Button playButton,stopButton;
MediaPlayer mp=null;
mp = MediaPlayer.create(this, R.raw.music);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout_xml_file);
playButton=(Button)findViewById(R.id.ShowDialog);
stopButton=(Button)findViewById(R.id.ShowToast);
playButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.playButton: // your button should have this id in xml file
Intent i = new Intent(MainActivity.this, CallActivity.class);
startActivity(i);
mp.setLooping(true);
mp.start();
break;
case R.id.stopButton: //your button should have this id in xml file
mp.stop();
break;
}
}
Upvotes: 0
Reputation: 1612
Your media player is within the scope of the method. Declare it in your class.
Class MediaDemo{
MediaPlayer mp=null;
mp = MediaPlayer.create(this, R.raw.music);
public void button1 (View v){
Intent i = new Intent(MainActivity.this, CallActivity.class);
startActivity(i);
mp.setLooping(true);
mp.start();
}
public void button2 (View v){
// your code goes here
mp.stop();
}
Upvotes: 2