As above, when I click a the british flag button on my app, it is meant to change langNumber to 0, so that a specific sound is played by wolvesfid. However, the value is never set to 0, but instead something else which causes the wrong sound to be played. in fact, even when I remove all code from my button, and leave only the break, the value still ends up changing, despite it playing the correct sound prior to pressing the button.
Relevant code:
case R.id.britishflagid:
langNumber = 0;
MediaPlayer mpB = MediaPlayer.create(MainActivity.this,
R.raw.langselect);
mpB.start();
case R.id.wolvesfid:
wolvesFThread.postDelayed(wolvesFRunnable, 0);
if (langNumber > 0.1) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this,
R.raw.wolvesstartd);
mp.start();
} else {
MediaPlayer mp = MediaPlayer.create(MainActivity.this,
R.raw.wolvesstartn);
mp.start();
}
adCount += 1;
wolvesFStart = 1;
break;
Runnable wolvesFRunnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
wolvesFTimer();
}
};
public void wolvesFTimer() {
try {
Thread.sleep(35000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (langNumber > 0.1) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this,
R.raw.wolvesfriendlytwod);
mp.start();
} else {
MediaPlayer mp = MediaPlayer.create(MainActivity.this,
R.raw.wolvesfriendlytwon);
mp.start();
}
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MediaPlayer ls = MediaPlayer
.create(MainActivity.this, R.raw.langselect);
ls.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (langNumber == 0) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this,
R.raw.wolvesfriendlyspawn);
mp.start();
}
if (langNumber == 1) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this,
R.raw.wolvesfriendlyspawnd);
mp.start();
}
wolvesFStart = 0;
}
Basically, why does the code not recognise langNumber == 0 ? All help appreciated.
You need to add break statement in the case block
case R.id.britishflagid:
langNumber = 0;
MediaPlayer mpB = MediaPlayer.create(MainActivity.this,
R.raw.langselect);
mpB.start();
break;
Related
I'm new to Android programming. I followed a mediaplayer tutorial but I'm now trying to make it more advance, the only problem is thats not working as expected.
When the song is finished it should start playing the next song, but doesn't update my seekbar (only updates Max) and it makes my buttons crash my app. I tried many things but can't fix it myself. If i press the next button however (before music track ends) the buttons and seekbar work.
What I'm want is my seekbar to reset for the new song and go again, and i want my buttons to work after the onCompletion next song.
Here my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
btPlay = (ImageButton) findViewById(R.id.btPlay);
btNxt = (ImageButton) findViewById(R.id.btNxt);
btPv = (ImageButton) findViewById(R.id.btPv);
btPlay.setOnClickListener(this);
btNxt.setOnClickListener(this);
btPv.setOnClickListener(this);
sb = (SeekBar) findViewById(R.id.seekBar);
updateSeekBar = new Thread() {
#Override
public void run() {
int TotalDuration = mp.getDuration();
int currentPosition = 0;
while (currentPosition < TotalDuration) try {
sleep(500);
currentPosition = mp.getCurrentPosition();
sb.setProgress(currentPosition);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
if (mp != null) {
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songlist");
position = b.getInt("pos", 0);
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
mp.stop();
mp.reset();
position = (position + 1) % mySongs.size();
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
sb.setMax(mp.getDuration());
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btPlay:
if (mp.isPlaying()) {
mp.pause();
btPlay.setImageResource(R.drawable.play);
} else {
mp.start();
btPlay.setImageResource(R.drawable.pause);
}
break;
case R.id.btNxt:
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
position = (position + 1) % mySongs.size();
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
sb.setMax(mp.getDuration());
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.btPv:
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
position = (position - 1 < 0) ? mySongs.size() - 1 : position - 1;
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
sb.setMax(mp.getDuration());
}
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
}
Errors (in android Monitor):
java.lang.IllegalStateException
I am working on a live streaming radio Android app...i have an array with 4 tracks, when i reach the end of the list suppose that the next button will represent " the last song" but it doesn't and crashes the app.
Here is the button code:
counter=0;
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn_next.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (counter < songurl.length) {
counter = counter + 1;
textview.setText(songurl[counter]);
try {
mediaPlayer.reset();
} catch (Exception ex) {
try {
mediaPlayer.setDataSource(songurl[counter]);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
} else {
Toast.makeText(MainActivity.this, "last song", Toast.LENGTH_SHORT).show();
}
}
});
One more question... in case I want to make it a closed loop when the app reaches the last song and I want to press next to start the list from the beginning how can I do it?
Thanks.
You can simply add a modulo (%) operator in your code
counter = counter++ % songurl.length
no need to add an extra if else block
btn_next.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
counter = counter++ % songurl.length
textview.setText(songurl[counter]);
try {
mediaPlayer.reset();
} catch (Exception ex) {
try {
mediaPlayer.setDataSource(songurl[counter]);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
});
One problem you have is that you are incrementing the counter just after you check that it is within the bounds, which means your safety check is useless. Move counter = counter + 1; to the end of the if statement.
As far as making it loop continuously, you can change it to counter = (counter + 1) % songurl.length; at the end of the if statement body.
Beyond the scope of the question you asked, there are some problems with your usage of MediaPlayer. It doesn't make any sense to have so much key logic in a catch statement. That means you expect the exception to happen. You should re-think what you are doing there.
You see you called mediaPlayer.setDataSource(songurl[counter]) in the catch block.
what if it will not have exception when you call mediaPlayer.reset()
try this:
try{
mediaPlayer.reset();
mediaPlayer.setDataSource();
mediaPlayer.prepareAsync();--or mediaPlayer.prepare();
(It depends on whether you load the url on the internet)
mediaPlayer.start(); -- if you call mediaPlayer.prepareAsync() you should call mediaPlayer.start() at the OnPreparedListener;
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
}
And if you still wondering, I suggest you to read something about MediaPlay's state.
PS If mediaPlayer is playing ,and you wanna let it play another one ,call mediaPlayer.stop() first;
To make the loop you should check in the onclicklistener that the if the counter is equal to the songurl.length which is i think the total number of song in the playlist.
int counter=0;
MediaPlayer mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn_next.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (counter < songurl.length) {
counter = counter + 1;
textview.setText(songurl[counter]);
try {
mediaPlayer.reset();
} catch (Exception ex) {
try {
mediaPlayer.setDataSource(songurl[counter]);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
} else if(counter == songurl.length) {
counter = 0;
// Toast.makeText(MainActivity.this, "last song", Toast.LENGTH_SHORT).show();
textview.setText(songurl[counter]);
try {
mediaPlayer.reset();
} catch (Exception ex) {
try {
mediaPlayer.setDataSource(songurl[counter]);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
}
});
in the elseif condition i have set the counter to 0. so that it will get in the loop.
this is my code, i am almost certain the problem is with the while loop.
public void start(View view) {
int currentPosition = 0;
player = MediaPlayer.create(this, R.raw.sound);
player.start();
int total = player.getDuration();
progressBar.setProgress(0);
progressBar.setMax(player.getDuration());
while (player != null && currentPosition < total) {
// try {
// Thread.sleep(500);
currentPosition = player.getCurrentPosition();
// } catch (InterruptedException e) {
// return;
// } catch (Exception e) {
// return;
// }
progressBar.setProgress(currentPosition);
}
}
public void stop(View view) {
player.stop();
}
whether or not i have the sleep intervals my result is the same; the sound starts playing but i cant stop it, and the progress bar doesn't move.
i would appreciate some help
I used this code in my app for using seekBar with MediaPlayer. It implements Runnable to keep the seekBar updating as the music plays. Take a look at the code:
public class MainActivity extends Activity implements Runnable,
OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
private Button stopMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.song2);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("play");
} else {
mp.start();
startMedia.setText("pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("play");
seekBar.setProgress(0);
}
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Thanks to: Sridhar Kulkarni
I used this code for play a sound by click on a button.
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sound/07.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
it's working well but i can't stop sound!
I use mp.stop(); .but click on button plays sound again!
when your onClickListener runs, the if statement checks after that other codes run. try to put an else statement after if you code should be like this :
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
}else{
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sound/07.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
I am new in android programming. I have a problem in stopping mediaplayer when I click the button for stop. I think I have some problem with my code because my sounds are looping that's is why mp.stop(); is not working or probably because of the sleep? I am not sure. Is there anyone who can help me with these? Thanks in advance.
Here is my code for stop:
bb5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
if (mp.isPlaying()){
mp.stop();
}
} // END onClick()
});
Here is my code for playing the sound:
protected void managerOfSound() {
int size = tempq.size();
for (int i = 0; i < tempq.size(); i++) {
String u =tempq.get(i);
//WHOLE
if (u.equals("a4")){
mp = MediaPlayer.create(this, R.raw.a4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}
}else if (u.equals("b4")){
mp = MediaPlayer.create(this, R.raw.b4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}
}else if (u.equals("c4")){
mp = MediaPlayer.create(this, R.raw.c4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}