Reputation: 1205
I do have 4 ToggleButtons in my application. All of them are for looping sounds in app. So, it means when I want to click on first ToggleButoon and its state will be on, music starts playing and keep looping untill its state is ON. The same with the rest of ToggleButtons. They might be ON at the same time (all of them) , so I'm planning to have 4 mediaplayers looping.
Here is my peace of code for first TogglleButton, so far no luck even with one....
public MediaPlayer resourcePlayer;
Context appContext = getApplicationContext();
resourcePlayer = MediaPlayer.create(appContext,R.raw.loop1);
.....
.....
public void onClick (View v){
switch (v.getId()) {
case R.id.toggleButton1:
boolean on = ((ToggleButton) v).isChecked();
if (on) {
resourcePlayer.start();
resourcePlayer.setLooping(true)
}
else {
resourcePlayer.stop();
}
break;
}
When I click on ToggleButton nothing happens, only states are changing on phone as i can see, LogCat is also clear. Thanks )
UPD1: Now it's looping, but when I change state it doesnt stop and keeps looping.
UPD2: resourcePlayer is a public in Main activity
UPD3: I have take out MediaPlayer variables to onCreate menthod so to do not make a duplicates. It plays and stops but only first time after that Logcat is giving error messages
MediaPlayer start called in state 0
....
....
MediaPlayer stop called in state 0
Upvotes: 0
Views: 2005
Reputation: 1568
you need to use resourcePlayer.setLooping(true); or false
for your UPD3:
because you are stopping the resourcePlayer it needs to be reassigned the sound source but in your case it only assigns in oncreate method which only called first time. so every time you want to play after stop need to reinitialize it.
Upvotes: 1
Reputation: 2678
i think it's because you keep on creating a new instance of the mediaplayer. so you are always sending the stop command to the newly created mediaplayer object not to the one currently playing.
Upvotes: 1