Mediaplayer : pause called in state 1 - Android Eclipse - java

I'm creating a MediaPlayer button in the ActionBar, wherein it is playing automatically when the app started and when I clicked it should be off. The problem now is that the sound is not playing and when I click the button there is an error in logcat saying...
UPDATED LOGCAT.
12-18 19:04:57.812: E/MediaPlayer(5673): attachNewPlayer called in state 32
Here is the code..
public class MainActivity extends Activity{
private MediaPlayer mp;
Item btnplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
isPlaying=false;//when the media file playing is completed isPlaying=false; is must
}
});
play(null);//you are calling play by launching
}
//inflate items in actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
boolean isPlaying = false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.btnplay) //whatever you named in xml
{
play(item);
}
return super.onOptionsItemSelected(item);
}
public void play(MenuItem menuItem) {
if (!isPlaying) {
try
{
AssetFileDescriptor afd = getAssets().openFd("caketown.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();//play sound
}
catch(Exception e) {
e.printStackTrace();
}
isPlaying = true;
}
else if (isPlaying) {
mp.pause();
isPlaying = false;
}
}
Here is the menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.xxx.MainActivity" >
<item
android:id="#+id/btnplay"
android:title=""
android:icon="#drawable/ic_action_volume_on"
android:onClick="play"
android:showAsAction="always"/>
<menu>
Please help me. I'm just new here. :(

1.Please initialize mp = new MediaPlayer(); in your onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play(null);//you are calling play by launching
}
2.change it to boolean isPlaying = false; because when app start it set as boolean isPlaying = false so it will play the audio and again you click on it for pause it will work as per your code
3.change this else if
else if (isPlaying) {
mp.pause();
isPlaying=false;
}
4.change this function too
public void play(MenuItem menuItem) {
if (!isPlaying && !isPaused) {
try {
if (mp == null) {
// mp.release();
// mp.reset();
mp = new MediaPlayer();
AssetFileDescriptor afd = getAssets()
.openFd("caketown.mp3");
mp.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
isPlaying = false;// when the media file playing is completed
isPaused = false;
// Toast.makeText(getApplicationContext(), "play completed",
// Toast.LENGTH_SHORT).show(); // isPlaying=false; is must
}
});
}
mp.start();// play sound
} catch (Exception e) {
e.printStackTrace();
}
isPlaying = true;
} else if (isPlaying) {
Toast.makeText(getApplicationContext(), "play paused",
Toast.LENGTH_SHORT).show();
mp.pause();
isPlaying = false;
isPaused = true;
length = mp.getCurrentPosition();
// and for resuming the player from the position where it stopped
// lately is done by:
} else if (isPaused) {
mp.seekTo(length);
mp.start();
isPlaying = true;
isPaused = false;
}
}

Initialize isPlaying to false to get your conditional working.
Initialize MediaPlayer only once to to get the stop/pause working instead of overlapping sounds. That is, move the mp = new MediaPlayer(); to onCreate() for example.

Related

Media Player error in RecyclerView

i have a RecyclerView that displays a list of songs and i have successfully implemented on click listener with it and verified it with logs. Now i want to play the song upon click event. When i first click on a item the songs starts to play but if i then tap on any other item the app simply crashes
Here is my RecyclerViewClickListener
SongAdapter songAdapter = new SongAdapter(getContext(), songsList, new RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Toast.makeText(getContext(), "You clicked on Ssong "+songsList.get(position).getSongName(), Toast.LENGTH_SHORT)
.show();
songPath = songsList.get(position).getUrl();
Log.v("Song Path", songPath);
if(mp.isPlaying())
releaseMediaResources();
playSong();
}
});
recyclerView.setAdapter(songAdapter);
Here is my playSong method
private void playSong () {
if(!songPath.equals("")) {
try {
mp.setDataSource(songPath);
} catch (Exception e) {
Log.e("Home Fragment", "Error setting song Url", e);
}
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
mp.release();
}
});
}
}
And here is my releaseMediaResources
private void releaseMediaResources() {
mp.stop();
mp.reset();
mp.release();
}
These are the errors
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.ashutosh.prototype4.HomeFragment.playSong(HomeFragment.java:159)
at com.ashutosh.prototype4.HomeFragment.releaseMediaResources(HomeFragment.java:192)
at com.ashutosh.prototype4.HomeFragment.access$100(HomeFragment.java:31)
at com.ashutosh.prototype4.HomeFragment$2.onClick(HomeFragment.java:94)
at com.ashutosh.prototype4.SongAdapter$1.onClick(SongAdapter.java:50)
According to me the main problem lies in setting up the media player because when i display only toast messages there's no issues at all but as soon as i implement media player to on click method the crash occurs
I will create every time the new MediaPlayer, but of course try to check, if there is not already existing instance for instance:
private MediaPlayer mediaPlayer;
private void playSong(String filePath) {
if (mediaPlayer != null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(filePath));
mediaPlayer.setVolume(DEFAULT_VOLUME_MUSIC, DEFAULT_VOLUME_MUSIC);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
});
}

Change button background from service

i'm following a step to play audio file from here link
and it works all right, the service in the link above is to play and stop audio.
The problem is i want to change a button background when the audio stop, so far i only got this in the activity that call the service:
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPlaying == false) {
isPlaying = true;
btnPlay.setBackgroundResource(R.drawable.stop_play_button);
playAudio();
} else {
isPlaying = false;
btnPlay.setBackgroundResource(R.drawable.play_button);
stopAudio();
}
}
});
You can declare on completetion listener on your player:
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
isPlaying = false;
btnPlay.setBackgroundResource(R.drawable.play_button);
stopAudio();
}
});

Issues with stopping MediaPlayer

My application contains one mediaplayer with one (play/pause) button in audio.xml , but the problem is that I am not able to find right code to stop MediaPlayer before the page gets destroyed and because of that the app crashes when i log in audio page (xml) and quit without running mediaplayer , here is the code i used:
public class audio extends Langue 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.audio);
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.espoir);
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
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// stop song
#Override
protected void onPause(){
super.onPause();
mp.stop();
finish();
}
}
Do something like this into the onPause() method for preventing crash
try{
mp.stop();
} catch(Exception e) {
}
finish();

Media player not starting after stopping

below is my code for media player. It doesn't start again after I stop. How to solve this? Even though I have called the prepare method before calling the start method. Also why doesn't the music stop playing even after I exit the programme. Please advice.
public class MainActivity extends Activity {
Button play,pause,stop;
CheckBox c1,c2,c3;
MediaPlayer song1,song2,song3;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);
stop=(Button)findViewById(R.id.button3);
c1=(CheckBox)findViewById(R.id.checkBox1);
c2=(CheckBox)findViewById(R.id.checkBox2);
c3=(CheckBox)findViewById(R.id.checkBox3);
song1=MediaPlayer.create(this, R.raw.finalcountdown);
song2=MediaPlayer.create(this, R.raw.invincible);
song3=MediaPlayer.create(this, R.raw.somewhereibelong);
builder=new AlertDialog.Builder(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void start(View view) throws IllegalStateException, IOException
{
if(c1.isChecked())
{
if(!song1.isPlaying())
{
song1.prepare();
song1.start();
}
else{
song1.start();
}
}
if(c2.isChecked())
{
if(!song2.isPlaying())
{
song2.prepare();
song2.start();
}
else{
song2.start();
}
}
if(c3.isChecked())
{
if(!song3.isPlaying())
{
song3.prepare();
song3.start();
}
else{
song3.start();
}
}
else{
builder.setMessage("Please mark a checkbox");
}
}
public void stop(View view)
{
if(c1.isChecked())
song1.stop();
else if (c2.isChecked())
song2.stop();
else if (c3.isChecked())
song3.stop();
else
builder.setMessage("Error message ");
}
public void pause(View view)
{
if(c1.isChecked())
{
song1.pause();
}
else if(c2.isChecked())
{
song2.pause();
}
else if(c3.isChecked())
{
song3.pause();
}
else
builder.setMessage("error message");
}
}
you need to put song1.release() and release methods for other songs inside the stop method. Refer the life cycle of media player for further info.
http://developer.android.com/reference/android/media/MediaPlayer.html
You have to release the player OnPause or OnDestroy method.
#Override
public void onDestroy() {
if(c1!= null)c1.release();
else if (c2!= null)c2.release();
else if (c3!= null)c3.release();
else
//something
}

Android Mediaplayer Error (-19, 0)

I try to replay a sound when I click on a button. But I get the Error (-19, 0) (what ever this means^^)
My code:
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.start();
}
});
What is my mistake?
I was getting the same problem, I solved it by adding the following code:
mp1 = MediaPlayer.create(sound.this, R.raw.pan1);
mp1.start();
mp1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
You need to release the previous media player before starting the new one.
Declare MediaPlayer as a instance variable and then:
mp = null;
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.start();
}
});
Or in your case, since you always play the same sound you don't need to release the player and create a new one, simply reuse the old one.
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.prepare(); // Blocking method. Consider to use prepareAsync
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.stop();
mp.start();
}
});
I sloved this problem by this code:
public static void playSound() {
mMediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor afd = context.getAssets().openFd("type.mp3");
mMediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
arg0.release();
}
});
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i hope to help you.

Categories