Reputation: 55
I have added two imageButton to my activity and on Clicking each one should play different sounds. But when I click on any Button the sound doesn't get play and the log shows error.
LOGCAT ERROR
09-30 15:19:07.436: D/dalvikvm(477): GC_EXTERNAL_ALLOC freed 629 objects / 50520 bytes in 180ms
09-30 15:19:10.226: E/MediaPlayer(477): start called in state 1
09-30 15:19:15.276: E/MediaPlayer(477): start called in state 1
Here is the piece of code which I wrote,
import android.media.MediaPlayer;
public class MainActivity extends Activity {
MediaPlayer mp;
ImageButton iV1,iV2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iV1 = (ImageButton)findViewById(R.id.iV1);
iV2 = (ImageButton)findViewById(R.id.iV2);
mp = MediaPlayer.create(this, R.raw.bud);
mp = MediaPlayer.create(this, R.raw.classic);
iV1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mp = new MediaPlayer();
mp.prepare();
mp.start();
}});
iV2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mp = new MediaPlayer();
mp.prepare();
mp.start();
}});
}
}
Please help me on this. Any help will be appreciated. I am New to this environment of Android.
Thanks in advance.
Upvotes: 0
Views: 211
Reputation: 479
It is easy to get in trouble when using MediaPlayer for button-sounds, especially with more buttons. I have described a solution using SoundPool here: How to Play sound when button is clicked in Android?
Upvotes: 0
Reputation: 4185
There are a couple of problems here. Firstly you're creating a new MediaPlayer object every time a button is pressed. You should remove these lines:
mp = new MediaPlayer();
mp1 = new MediaPlayer();
You already created the objects using the static create method.
Also as already mentioned, you need to call prepare before you call start:
mp.prepare();
mp.start();
Upvotes: 1
Reputation: 1815
This is a state machine issue, as the log clearly says :
09-30 15:19:10.226: E/MediaPlayer(477): start called in state 1
Refer : http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram
e.g., I dont see, where you are calling
MediaPlayer.setDataSource();
MediaPlayer.Prepare()
Upvotes: 1