Play and stop MediaPlayer in Android - java

Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
MediaPlayer mp = MediaPlayer.create(main.this, R.raw.lastmohican);
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mp.isPlaying()) {
mp.stop();
} else {
mp.start();
}
}
}
I can play this music by one click and with another click music is stopped, but when I click together music does not start. Any idea why?

I'm not sure I understand your problem, but if you are wondering why the audio will not start back up after you press the button a third time, it is because you are calling stop() on the media player when you should be calling pause(). Stop requires you to prepare the media again before you can begin playback. Have a look at the MediaPlayer Documentation. If that is not your problem you need to provide a better description.

Its solved you should change code for this type
if (mp.isPlaying()) {
mp.stop();
mp.prepareAsync();
mp.seekTo(0);
} else {
mp.start();
}

Related

android app crashes when starting/stopping media

I am writing a small practice app that plays a sound clip when a button is tapped. In my previous code, this amounts to just the creation of a MediaPlayer object and a call to mp.start() to start the audio.
This works, but now I would like that same button to play only when no sound is playing yet. If sound is playing, stop the audio. A play/stop button.
I tried to do this using the following code:
```
public class MainActivity extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goButtonClicked(View v) {
if(mp == null) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.wordt);
}
if(mp.isPlaying()) {
mp.stop();
mp.release();
}
else {
mp.start();
}
}
}
```
However now when I run the app, the app crashes when I tap the button. Where did I go wrong?
Just change your code like this,
public void goButtonClicked(View v) {
if(mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.wordt);
}
....
}
What happens here is, MediaPlayer mp = ... means you are creating a local variable inside if condition. But still your field variable is null. And when the app executes the second if condition, it throws a NullPointerException.
You didn't initialize your first mp object, so you see nullPointerException,
and you can delete second mp object

Android: button is not changing to pause state when i click

i have coded for media player and it is playing song .In the front end only image button is used and hardcoded as play button
when i click again it has to change image to pause state but the button which i have used is playing the song two times simultaneously whenever i click on it which is wrong
but i need the song to be paused so whereever i used
mp.start();
function which will be start to play the music from the url i added the code as
if(!mp.isPlaying()){
mp.start();
buttonPlayPause.setBackgroundResource(R.drawable.pause);
}else {
mp.pause();
buttonPlayPause.setBackgroundResource(R.drawable.play);}
but when i click the play button it starts playing and again if i click the button again it starts playing two times simultaneously
please help me how should i start and pause the mp3 file which i have displayed it in url it is not going to else block itself should i use different function
the full code of the project is
public class MainActivity5 extends Activity implements OnClickListener,
OnPreparedListener, OnErrorListener, OnCompletionListener {
MediaPlayer mp;
ProgressDialog pd;
Button bt;
ImageButton iv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main5);
iv = (ImageButton)findViewById(R.id.play);
iv.setOnClickListener(this);}
#Override
public void onPrepared(MediaPlayer mp)
{
Log.i("StreamAudioDemo", "prepare finished");
//pd.setMessage("Playing.....");
//mp.start();
/*if(mp.isPlaying()== true)
{
mp.start();
iv.setImageResource(R.drawable.pause);
}
else
{
mp.pause();
mp.release();
iv.setImageResource(R.drawable.play);
}*/
}
#Override
public void onClick(View v) {
try
{
pd = new ProgressDialog(this);
pd.setMessage("Buffering.....");
//pd.show();
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setDataSource("http://192.168.1.138/Android/music/vande.mp3");
mp.prepareAsync();
mp.setOnCompletionListener(this);
}
catch(Exception e)
{
Log.e("StreamAudioDemo", e.getMessage());
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
pd.dismiss();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
pd.dismiss();
Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
}}
thanks for your help in advance
i have commented some code above i have to re correct it
you can have a try at your onclickListener,when this player is playing,if you want to pause it ,you should to call MediaPlayer.pause() ,if you want to release it data,you can call MediaPlayer.release(),then ,you can play next music.
use this
public void onPrepared(MediaPlayer mp)
{
Log.i("StreamAudioDemo", "prepare finished");
//pd.setMessage("Playing.....");
// mp.start(); - this should be removed
if(mp.isPlaying()== true)
{
mp.pause();
iv.setImageResource(R.drawable.pause);
}
else
{
mp.start();
mp.release();
iv.setImageResource(R.drawable.play);
}
}

Replaying the sound as many times as button is clicked

I have the following code:
if (someId.matches("A") || someId.matches("a")) {
tvLetCap.setText("A");
tvLetLow.setText("a");
ivLetterIcon.setImageResource(R.drawable.apple);
btnDisplayWord.setText("A is for APPLE");
mpSound = MediaPlayer.create(this, R.raw.sound);
mpSound.setLooping(false);
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
/*try {
Uri uri = Uri.parse("android.resource://com.mypack.testing/" + R.raw.sound);
mpSound.setDataSource(getApplicationContext(),uri);
mpSound.prepare();
*/
mpSound.start();
btnPlay.setVisibility(View.GONE);
btnStop.setVisibility(View.VISIBLE);
btnStop.setOnClickListener(stopSound);
/*}
catch (IOException e){
Log.e("REPLAYING", "prepare() failed");
}*/
}
});
mpSound.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mpSound.release();
btnPlay.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.GONE);
}
});
}
It plays fine with the codes commented out but whenever I try to replay the file my app FC. The sound file is located in res/raw/sound.mp3
How can I modify the code so it plays as many times as the btnPlay is pressed.
You've released the media player. If you want to reuse it, don't do that.
There are some methods for mediaplayer...
http://developer.android.com/reference/android/media/MediaPlayer.html
Maybe you need to use mpSound.reset() in onClick method for button (some time ago i had such mistake :p)? :)

How to disable another button when sound clip is over in Android?

I'm implementing Android application for creating media player.I have run the application properly for playing the music on button click . When i click the button_Start the music is start to playing and click on the same button_Start for pause and resume/start.when the button_Start is click my button_Second is disable and when button_Start click for pause then button_Second is disable is properly . But I want when sound clip is over my button_Second is enable and button_Start is disabled .I'm getting error when i run the app (IllegelStateException) . I don't know how can i do this.Can any one help me.Thanks in advanced.
Here is my code .This is y Audio_Activity class.
public class Audio_Activity extends Activity
{
private MediaPlayer mp;
Button btnStartStop ;
Button btnChapter ;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
mp=MediaPlayer.create(this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
System.out.println("B4 button Click!!!!");
System.out.println("After Button click !! ");
if(mp!=null)
{
mp.stop();
mp.release();
System.out.println("Media Player Is Stop and release");
btnChapter.setEnabled(true);
System.out.println("btnChapter is enabled when media player is
release !!!");
}
btnStartStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(mp.isPlaying())
{
if(mp!=null)
{
mp.pause();
imgVw.setImageResource(R.raw.images1);
btnChapter.setEnabled(true);
}
}
else
{
// Resume song
if(mp!=null)
{
mp.start();
imgVw.setImageResource(R.raw.teddy_two);
btnChapter.setEnabled(false);
}
}}
});
}
public void init()
{
imgVw=(ImageView)findViewById(R.id.display_Images);
btnStartStop=(Button) findViewById(R.id.btnPause_Resume);
btnChapter=(Button) findViewById(R.id.btnChapter);
}
}
You can disable the button when the sound clip starts and then use the setOnCompletionListener method of the MediaPlayer class (link) to register a handler that will enable the button again. Hope that helps:)

Stop MediaPlayer

I made an android application where you can click buttons to play sounds. Every time, you click the button, a new MediaPlayer is getting created and the problem is, when you push a button during another sound is still playing, they are playing at the same time, but I want, that the previous sounds stops when you push a button. I already tried this code but my application crashes every time I press the button:
MediaPlayer mp;
Button button;
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()){
mp.stop();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});
Is there a way to solve my problem?
It might be crashing because 'mp' is not initialized. Try this:
#Override
public void onClick(View v) {
//if mp exists and is playing...
if(mp != null && mp.isPlaying()){
mp.stop();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});
EDIT You could also avoid checking for null by initializing 'mp' when you declare it on top.
For instance, instead of checking if mp != null. Change your declaration of 'mp' from:
MediaPlayer mp;
to
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
and your onclick method could look like:
public void onClick(View v) {
if(mp.isPlaying()) {
mp.stop();
}
//start mp from beginning
}
It seems like starting too many MediaPlayer isn't good, because when i click the sounds a couple times, the app crashes. I already changed mp.start to mp.reset and release.
Notes
You have to release the player before creating a new one
I would not bet on isPlaying() check to stop the player; since you don't need it release it!
Code
#Override
public void onClick(View v) {
if(mp != null) {
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});

Categories

Resources