I've been struggling today to make make my button sound. I wanted to make button to play sound when you click on it, and when you click again to stop playing sound First part Is working, but then I added
if(mpButtonClick1.isPlaying())
{
mpButtonClick1.stop();
}
else
{
mpButtonClick1.start();
}
And since I added that part, when I click on button nothing happens. No sound. Eclipse is not showing me any error. Here is my activity
package com.example.splashzor;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Prvi extends Activity{
MediaPlayer mpButtonClick1;
@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);
mpButtonClick1.isPlaying();
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.stop();
}
else
{
mpButtonClick1.start();
}
}
}
});
}
}
I would appreciate if you show me what I did wrong and how to fix it.
Remove the mpButtonClick1.start();
call before your if/else
block.
Otherwise whenever you click the button you always start it and then immediately stop it, resulting in no sound being played.
The logic should be:
@Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.pause();
}
else {
mpButtonClick1.start();
}
}
EDIT : also change stop()
to pause()
. Calling stop()
means it enters the stopped state and cannot be played again until you call prepare()
http://developer.android.com/reference/android/media/MediaPlayer.html
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.