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
}
Related
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.
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();
}
}
}
});
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;
I'm building a Android app that streams simple radio station.
EDIT: I added the OnCreate event and the init() function.
on create:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
play_or_pause();
}
the init() function:
public void init() {
mediaPlayer = new MediaPlayer();
stream_url = "http://the_radio_station.m3u8";
playing_now = false;
fb_error = "";
}
on created I'm calling the AsyncTask method:
play_or_pause();
the AsyncTask method:
public class play_or_pause_AsyncTask extends
AsyncTask<Boolean, Integer, String> {
#Override
protected String doInBackground(Boolean... params) {
// TODO Auto-generated method stub
if (!params[0]) {
fb_error = "";
try {
if (mediaPlayer.isLooping() || mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
fb_error = String.valueOf(mediaPlayer.isPlaying());
mediaPlayer.setDataSource(stream_url);
mediaPlayer.prepare();
mediaPlayer.start();
playing_now = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
fb_error += e.toString();
} catch (SecurityException e) {
// TODO Auto-generated catch block
fb_error += e.toString();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
fb_error += e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
fb_error += e.toString();
}
} else {
mediaPlayer.stop();
playing_now = false;
}
return fb_error;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(MainActivity.this, fb_error, Toast.LENGTH_LONG).show();
}
}
when I'm opening another Activity and coming back to the MainActivity(which making the stream) its starting to run the streaming again without stooping the old one.
I reed many posts here, the only suggestion was to use:
if ( mediaPlayer.isPlaying()) mediaPlayer.stop();
but it ain't helping (someone wrote that the mediaPlayer object is strange, you cant tell what is the objecct real status - Like if the .isPlaying() is true / false).
so what I can do in this situation?
try this way i use everytime
#Override
public void onStop() {
super.onStop();
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
have the following code to run an mp3 podcast
public void playPodcast( final Uri data){
new Thread (new Runnable(){
public void run() {
if(!mediaPlayer.isPlaying()){
try {
mediaPlayer.setDataSource(getApplicationContext(), data);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
duracaoPodcast = mediaPlayer.getDuration();
mediaPlayer.start();
if(!(controlTimer >= 1)){
timer();
controlTimer++;
}
primarySeekBarProgressUpdater();
}
}
}).start();
}
and to close the User Intent have:
voltar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
mediaPlayer.stop();
}
});
the problem occurs when the User closes the intent that all the return button phones with android is because it does not:
finish();
mediaPlayer.stop();
makes only:
finish();
and so the audio is still playing, even if I go back to that intent the pause:
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
frame.setVisibility(View.INVISIBLE);
}
}
});
button does not work, and if I press the play he starts a new audio on top of that emptied playing,
any idea how to solve?
put mediaPlayer.stop(); in activity onStop() Method as far as i understood your question.