Trying to use the same button to play+pause music - android

I have recently tried to create a button that says "Play", and when this button is pressed, I wanted it to play the music then change the text to "Stop", but it throws an error and quits the app. Here is my code:
mPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ourMusic.isPlaying()){
ourMusic.pause();
mDisplay.setText("Play");
}else{
ourMusic = MediaPlayer.create(MainActivity.this, R.raw.killthenoise);
ourMusic.start();
mDisplay.setText("Stop");
}
}
});
So if you press the button once it should play, press it again it should stop the music. There is no errors in the actual coding.
Here is my logcat: http://pastie.org/7970711
I am new to this stuff, so I don't know too much of whats going on. Any help would be appreciated.

Use this instead:
#Override
public void onClick(View v) {
if (ourMusic == null) {
ourMusic = MediaPlayer.create(MainActivity.this, R.raw.killthenoise);
}
if(ourMusic.isPlaying()){
ourMusic.pause();
mDisplay.setText("Play");
}else{
ourMusic.start();
mDisplay.setText("Stop");
}
}
Basically don't:
Recreate ourMusic everytime there is a click to play
Try to use ourMusic when it isn't instantiated.

Add a global variable boolean flag=false;
if(flag==false)
{
mp=MediaPlayer.create(this, R.raw.abc);
mp.start();
playbutton.setText("Pause");
flag=true;
}
else if(mp.isPlaying()&&flag==true)
{
mp.pause();
playbutton.setText("Play");
flag=false;
}
This code will work if you want to use the same button as PLAY/PAUSE in your app.
Hope this helps.

Related

My Quit Button is not playing the sound when i click it, except this all the button are playing sound. Can anyone solve this problem?

// This is my app exit button it destroys the activity and exits the user from an app. I want to //play a sound when I click this button but unfortunately, the sound is not playing and the activity //destroys. Please help me in solving this issue. Except for this button, all my button sound is working.
// This is my second activity, in this activity, I have used a button for quitting the app but I also //want the button to play a sound when the button is clicked by user. But it is not playing the sound and //quits the app which destroys activity. please tell me how to play the sound on my exit button during //the click
mExitApp = (Button)findViewById(R.id.exit_app);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sample2);
mExitApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
ScoreActivity.this.finish();
System.exit(0);
}
});
A quick and dirty way would be to wait for the sound to end playing before finishing the activity/process.
public void onClick(View v) {
mp.start();
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
ScoreActivity.this.finish();
System.exit(0);
}
}, 300);
}
A more cleaner solution would probably involve a MediaPlayer.OnCompletionListener.
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
finish(); // finish current activity
}
});
Or you could play the sound in a foreground/background service. But then you shouldn't kill the entire process (System.exit(0)) like you do now ofc.

How to automatically close media when switching to another class in Android

I have an Android app. I created a class for the media menu. When I return from the media menu to the main activity, the sound works, but if I return to the media menu again, the sound does not cut off. Moreover, if I then press the pause button, the application crashes!
How can I solve this issue? I have thought of a lot of solutions except that I cannot create a destroy function because it is not present in the options.
Here is my code:
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mdp == null) {
mdp = MediaPlayer.create(context, d.getsound());
mdp.start();
} else {
mdp.pause();
mdp = MediaPlayer.create(context, d.getsound());
mdp.start();
}
}
});
Give this a shot my friend
#Override
public void onPause(){
super.onPause();
mdp.stop();
mdp.release();
}

Mediaplayer - stop current audio when clicking on new audio

Im a newbie to android studio (programming at general) but i want to build a mediaplayer for learning purposes.
I have a a list of local music in a listView that contains 2 images 'play, pause and stop button'.
This is how my app works:
Click on playbutton -> start music
Click on pausebutton -> pause music
Click on stopbutton -> stop music
Very simple. BUT! the thing is -> when i pause a song and want to play another song in my list then it just resume the first song i clicked on.
I want it to release the first song and start the other one i click on.
This is my code:
// play music
viewHolder.playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (flag) {
//get song you clicked on
mediaPlayer = MediaPlayer.create(context, song.getSong());
//set boolean to false so it can get ANOTHER song when
//clicked
flag = false;
Toast.makeText(context, "Playing" + song.getName(),
Toast.LENGTH_LONG).show();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.playB.setImageResource(R.drawable.play);
} else {
mediaPlayer.start();
viewHolder.playB.setImageResource(R.drawable.pause);
}
}
});
// stop
viewHolder.stopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!flag) {
mediaPlayer.stop();
mediaPlayer.release();
flag = true;
}
viewHolder.playB.setImageResource(R.drawable.play);
}
});
Your logic is a little bit wrong. When you create the MediaPlayer you set flag to false and as long as you do not stop playback flag doesn't change. But your MediaPlayer creation depends on it.
For future improvements (maybe when you're more confident in working with MediaPlayer and Android) you should take a look at a more "self-made" approach instead of MediaPlayer.create(...) cause this method is calling MediaPlayer's prepare() method that is going to eventually make your app extremely slow or crash it when loading big files.
Example according to comments
I assumed songis going to be the class object.
// class variable will hold the currently loaded song
private Song mCurrentSong;
[...]
viewHolder.playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// MediaPlayer has not been initialized OR clicked song is not the currently loaded song
if (mCurrentSong == null || song != mCurrentSong) {
// Sets the currently loaded song
mCurrentSong = song;
mediaPlayer = MediaPlayer.create(context, song.getSong());
Toast.makeText(context, "Playing" + song.getName(),
Toast.LENGTH_LONG).show();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.playB.setImageResource(R.drawable.play);
} else {
mediaPlayer.start();
viewHolder.playB.setImageResource(R.drawable.pause);
}
}
});
viewHolder.stopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// If currently loaded song is set the MediaPlayer must be initialized
if (mCurrentSong != null) {
mediaPlayer.stop();
mediaPlayer.release();
mCurrentSong = null; // Set back currently loaded song
}
viewHolder.playB.setImageResource(R.drawable.play);
}
});

Losing the control of the mediaplayer when the activity is recreated

In my project I am trying to make a media player which plays a shoutcast stream. Everything seemed to be working well until I pressed the back button on my device, which I think stops the activity and causes the device to recreate the activity when launched again. The problem is , when the activity is recreated , I lose the control of the mediaplayer and a new mediaplayer is created.
I need to be able to have the mediaplayer's control back at that point. How is it possible?
This part of code belongs to onCreate
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
if (mediaPlayer == null){
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getString(R.string.yayin));
} catch (Exception e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
}
if(!isPlaying){
btn.setBackgroundResource(R.drawable.oynat);
}
else{
btn.setBackgroundResource(R.drawable.durdur);
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isPlaying){
playOnReady();
isPlaying = true;
btn.setBackgroundResource(R.drawable.durdur);
}
else{
mediaPlayer.reset();
isPlaying = false;
btn.setBackgroundResource(R.drawable.oynat);
}
}
});
This part of code belongs to the function playOnReady()
private void playOnReady(){
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
Take a look at the Android Activity lifecycle flowchart: https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You need to account for the path where onPause is called when you leave the Activity and then onResume is called when you enter it again. The solution for you could be as simple as moving some/all of your code from onCreate into onResume.
Using this tutorial I have managed to build a service which handles the mediaplayer that I can have the control of anytime I need.

Android MediaPlayer Starts sound but doesn't start up again

I made a basic app with 2 buttons, start and stop. When I start the app and hit the start button the sound starts, and when I the end button it stops, BUT if I try to start up again with the start button it doesn't start again.
Code:
buttonStart = (Button)findViewById(R.id.ButtonStart);
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onClickButton(buttonStart);
}
});
buttonEnd = (Button)findViewById(R.id.ButtonEnd);
buttonEnd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onClickButton(buttonEnd);
}
});
beat = MediaPlayer.create(this, R.raw.beat);
public void onClickButton(Button button){
if(button == buttonStart){
beat.start();
beat.setLooping(true);
}
else if(button == buttonEnd){
beat.stop();
//beat.setLooping(false);
}
}
if you stop the media player then the instance of the media player is destroyed so if you want to play again. Then you have to create the instance of media player again. Put this code in your buttonStart
beat = MediaPlayer.create(this, R.raw.beat);
beat.start();
beat.setLooping(true);
Best of luck and don't forget to tick that this answer is useful to you.

Categories

Resources