MediaPlayer keep playing even button disabled - java

I tried most of options avialable on stackoverflow, could you please help me!
I have a button which plays MediaPlayer instance when clicked, but the problem if I click double-click or clicked during playing media it will play two times even i set the button.setEnable(false) and button.setClickable(false), below is the code in Main.java, and I have set in xml android:onClick="playMedia"
MediaPlayer playMedia;
private void playGeneric(MediaPlayer mp, int name, Button button) {
button.setEnabled(false);
button.setClickable(false);
mp = MediaPlayer.create(this, name);
mp.start();
while (mp.isPlaying()) {
}
mp.stop();
mp.release();
mp = null;
button.setEnabled(false);
button.setClickable(false);
}
// play the Media
public void playMedia(View button) {
playGeneric(Media, R.raw.Media, (Button) findViewById(R.id.button1));
}
thanks a lot

1- You should have a single (preferably static) MediaPlayer instance per your activity/service
2- This loop while (mp.isPlaying()) is extremely bad practice, you just need to listen to the appropriate event
3- Before creating a new MediaPlayer instance you have to check that if the current one is not null then stop and release it
To solve your code you can do the following:
1- Let your class implements OnCompletionListener and override the method onCompletion(MediaPlayer mp) to be notified when the MediaPlayer finished and clean the resources (but you need to clean it as well when your activity/service get destroyed)
2-
static MediaPlayer playMedia;
private void playGeneric(MediaPlayer mp, int name, Button button) {
button.setEnabled(false);
button.setClickable(false);
if(mp !=null){
mp.stop();
mp.release();
}
mp = MediaPlayer.create(this, name);
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
playMedia = null;
button.setEnabled(true);
button.setClickable(true);
}

Related

I have a problem with Media Player when playing the audio, it does not stop even when I exit the application How do I release this code?

enter code here
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.seekTo(0);
}
});
}
#SuppressLint("DefaultLocale")
private String convertFormat(int duration) {
return String.format("%02d:%02d"
, TimeUnit.MILLISECONDS.toMinutes(duration)
,TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}
}
enter code here
I think you are creating a Mediaplayer instance everytime. Make sure that instead of the instantiation is
MediaPlayer mp;// above the onCreate section
mp=MediaPlayer.create(this, R.raw.animal_kit);
instead of
MediaPlayer mp=MediaPlayer.create(this, R.raw.animal_kit);

My android App stop playing sound on button tap after some time

Hello there, i have just created a basic android app which plays different musics on button tap..
The app just worked fine for the first couple of seconds but when i just keep on tapping and tapping , at some point it stops playing the music and just crashed...
I am unable to figure out what the problem is ..Please help me make it work..
Thanks.
Here is my code :-
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
public void PlayMusic(View view)
{
int ID = view.getId();
String NameID = view.getResources().getResourceEntryName(ID);
int sound= getResources().getIdentifier(NameID,"raw","com.example.pickachu.mypatatap");
mediaPlayer = MediaPlayer.create(this,sound);
mediaPlayer.start();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The sound is not playing after multiple taps because you must be getting IllegalStateException because you are not releasing the Mediaplayer object and Mediaplayer Lifecycles are not managed properly when you tap multiple times.
You can use setOnCompletionListener(MediaPlayer.OnCompletionListener listener) to release mediaPlayer after completion of sound as:
mediaPlayer = MediaPlayer.create(this,sound);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
mediaplayer = null;
}
});
mediaPlayer.start();
pass uri instead string
mediaPlayer= MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/music.mp3"));
mediaPlayer.setLooping(true);
mpintro.start();

Android media player not working as expected

I am very new to android just started with Android currently referring the below code from past 2 days, not able to fix the issue.
Code:
https://github.com/quocnguyenvan/media-player-demo
Issue: Let's say we 4 Songs in the ListView when we click on the first song play it for some time and pause it without clicking on stop.
As soon as we click on the second song the first song starts playing we cannot play the second song unless we click on stop of the first song How to solve this issue.
The issue with code not able to figure out and fix it.I have referred many posts before posting on StackOverflow but could not make it, any suggestion or guidance is highly appreciated.
Problematic code:
// play music
viewHolder.ivPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(flag){
mediaPlayer = MediaPlayer.create(context, music.getSong());
flag = false;
}
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.ivPlay.setImageResource(R.drawable.ic_play);
} else {
mediaPlayer.start();
viewHolder.ivPlay.setImageResource(R.drawable.ic_pause);
}
}
});
// stop
viewHolder.ivStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!flag) {
mediaPlayer.stop();
mediaPlayer.release();
flag = true;
}
viewHolder.ivPlay.setImageResource(R.drawable.ic_play);
}
});
These are the steps I used for playing song you can try to sync with my steps to resolve the error.
private void initMembers() {
//initialize the members here
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//media prepare
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
//media player prepared
togglePlayPausePlayer();
}
});
//media completion
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(final MediaPlayer mediaPlayer) {
//handle the media play completion
handleOnCompletionLogic();
}
});
}
after that whenever I try to play the song. I call this method.
public void playMusic(final MusicModel musicModel) {
//here play the music with data in below
try {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.reset();
mMediaPlayer.setDataSource(musicModel.getUrl());
mMediaPlayer.prepareAsync();
} catch (IOException | IllegalStateException exp) {
exp.printStackTrace();
showMessage(getString(R.string.error_unable_play));
}
}
above resets the playing song and prepare the player for another song.
and OnPreparedListener it calls the togglePlayPausePlayer() which play and pause the song accordingly.
private void togglePlayPausePlayer() {
//here handle the logic for play and pause the player
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
setPlayAndPause(false);
} else {
mMediaPlayer.start();
setPlayAndPause(true);
}
}
The key is we initialize the player and set an onPrepareListener for the media player to get prepared and then play the song, which will check if it's playing then it will stop and else it will play.
hope this may help you.
For on click on ListView you need to reset the media player, change the data source and start playing with new song.
mp.reset();
mp.setDataSource("song you selected from ListView");
mp.prepare();
mp.start();

android media player unresponsive

This is my code, I tried ti build simple application that plays a song whenever I click one button (clicking twice will play the song a new from the beginning) & stop playing when another button is pushed.
I wanted that when the user put the activity in the background the media player will "save its state" - continue playing/not playing - and when the activity returns to the foreground the interaction will remain the same.
Instead it works fine until I put the activity in the background (then it keeps playing/not playing) but when I return it back it seems like "a new media player object was created" and if I click play while the song is played, it starts to play the song from the beginning simultaneously with the previous one, and clicking stop - stopping only the new "instance" of the song. Like I loose connection with the media player after the activity is in the background.
what could be the problem?
public class MainActivity extends ActionBarActivity {
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonStart = new Button(this);
Button buttonStop = new Button(this);
buttonStart.setText(R.string.button_start_text);
buttonStop.setText(R.string.button_stop_text);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPlaying();
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
}
});
ViewGroup layout = (ViewGroup) findViewById(R.id.mainLayout);
layout.addView(buttonStart);
layout.addView(buttonStop);
}
void startPlaying(){
stopPlaying();
mediaPlayer = MediaPlayer.create(this,R.raw.dreams);
mediaPlayer.start();
}
void stopPlaying(){
if (mediaPlayer != null){
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I changed the code also, like this (now there are 3 buttons: play, stop, pause:
void startPlaying(){
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.dreams);
}
mediaPlayer.start();
}
void stopPlaying(){
if (mediaPlayer != null){
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.prepare();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
void pausePlaying(){
if (mediaPlayer != null) mediaPlayer.pause();
}
but still same behaviour.
Some insight I got:
before the user place the activity in the background the member mediaPlayer is some constructed android object.
when the activity returns to the foregound mediaPlayer is null.
Why is this?
Maybe I got wrong the idea of activity but I thought it keeps its members with their values during its life cycle.
Your are creating and destroying your mediaplayer everytime. Try to create two methods for pause and resume/start like that.
below you can find the code that is working fine for me. I am developing a game that starts a main theme when the activity loads. Each time the activity resumes, the media player continue to play the song at the paused position. I override onDestroy() to stop, onResume to start/resume and onPause() to pause when the activity goes Background.
public MediaPlayer mp=null;
#Override
protected void onDestroy() {
if (mp!=null)
mp.stop();
super.onStop();
}
#Override
protected void onResume() {
super.onResume();
if (mp==null){
self=this;
Thread thMusic= new Thread(new Runnable(){
public void run(){
mp= MediaPlayer.create(self,R.raw.dizzy );
mp.start();
}
});
thMusic.start();
}
else
mp.start();
}
#Override
protected void onPause() {
if (mp!=null)
mp.pause();
super.onPause();
}
i hope this will help you.
http://developer.android.com/guide/components/activities.html
Saving activity state gives a detailed information that could explain what happened.
In short when activity is in the background it might be killed and created again by OS when user navigate it back to foreground.
onSaveInstanceState() should be implemented unless only UI objects are restored
but not class members

How can I make android mediaplayer play sound?

I don't know why it doesn't works, there is no error logged in logcat, but I cannot hear a sound.
public static void DeclararSonido(int numero, Context contexto){
switch(numero){
case 0:
mp = MediaPlayer.create(contexto, R.raw.alan);
break;
}
}
public static void TocarPiedra( int posicion, Context contexto){
DeclararSonido(posicion, contexto);
mp.start();
mp.stop();
mp.release();
}
public static void TocarSirena(Context contexto){
MediaPlayer mp2= MediaPlayer.create(contexto, R.raw.doh);
mp2.start();
mp2.stop();
mp2.release();
}
If I erase mp2.stop(); and mp2.release(); AND mp.stop(); and mp.release(); the app plays the sound, but the file is not released...
You certainly do not want to Start and then Stop right away..
The problem is that you are executing these right after each other:
mp.start(); // starts playback
mp.stop(); // .. then stops immediately ..
mp.release();
You should call start, and then when the sound is done playing, release. You can use the Completion event to hook up a listener and release there:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer player) {
player.release();
}
})
Mediaplayer.create():- creates the new object of mediaplayer .this object is having music file from raw folder which is to be played when start() method is called
Mediaplayer.start():- *starts playing music* if object Mediaplayer is initialized .otherwise gives exception.
Mediaplayer.stop() :-*stops* the current ongoing music with that object.
Mediaplayer.release():-the music file path is no longer associated with Mediaplayer object. so u need to reallocate memory and all. mind it mediaplayer would not be null .
go here and see the state diagram of mediaplayer
Now what you are doing is that starting the song and directly stopping it .I would suggest you to create button , and when button is pressed stop the mediaplayer.
Other way is already given by Miky Dinescu that setoncompletelistner.
so, do as follows
public static void DeclararSonido(int numero, Context contexto){
switch(numero){
case 0:
mp = MediaPlayer.create(contexto, R.raw.alan);
break;
}
}
public static void TocarPiedra( int posicion, Context contexto){
DeclararSonido(posicion, contexto);
mp.start();
mp.setOnCompleteListener(new OnCompleteListener(){
public void OnCompletion(MediaPlayer mp){
mp.stop();
mp.release();
}});
}
public static void TocarSirena(Context contexto){
MediaPlayer mp2= MediaPlayer.create(contexto, R.raw.doh);
//Alomejor es por la extension
mp2.start();
mp2.setOnCompleteListener(new OnCompleteListener(){
public void OnCompletion(MediaPlayer mp){
mp2.stop();
mp2.release();
}});
}

Categories