I am trying to develop android sound application, I am sort of new into development so I am stuck on 1 little problem. I made On Button click to play sound, but I want when I click on that button again, I want it to stop Media player. I would appreciate if you could help me with the script.
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mpButtonClick1.start();
}
});
}
if(mpButtonClick1.isPLaying()){
mpButtonClick1.start();
}else{
mpButtonClick1.stop();
}
And as a general tip, check out the documentation of the classes you use, you might have found the solution yourself... http://developer.android.com/reference/android/media/MediaPlayer.html#isPlaying()
You can used MediaPlayer.isPlaying()
to determine what your button should do when it is clicked.
@Override
public void onClick(View v)
{
if(mpButtonClick1.isPlaying())
{
mpButtonClick1.stop();
}
else
{
mpButtonClick1.start();
}
}
You can use the isPlaying method.
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mpButtonClick1.isPlaying())
stopPlaying();
else
mpButtonClick1.start();
}
});
}
private void stopPlaying() {
if (mpButtonClick1 != null) {
mpButtonClick1.stop();
mpButtonClick1.release();
mpButtonClick1 = null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
boolean isOn = false;
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
is(!isOn) { // if not playing
mpButtonClick1.start(); // start
isOn = true; // now it is
} else { // otherwise it's already on
mpButtonClick1.stop(); // turn it off
isOn = false; // now it's off
}
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.