Android: How to stop all active Media Players? - java

I have a app with some buttons.
On a Tab on one of these buttons a sound will be played.
Example code:
public void button1(View a) {
MediaPlayer mp1 = MediaPlayer.create(Home.this, R.raw.button1);
mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp1.start();
}
public void button2(View b) {
MediaPlayer mp2 = MediaPlayer.create(Home.this, R.raw.button2);
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp2.start();
}
...
Is there a way to stop all MediaPlayers for example on a "Stop all Sounds"-Button?

You can create a ArrayList where you put all your mediaplayers in and stop them while looping.

Related

MediaPlayer freezing application in loop

ISSUE:
I have problem with my code. I want to loop my MediaPlayer, but when I do it with while loop, MediaPlayer playing, but application is freezed. I know, mediaplayer have setLooping method, but I must do it with while loop because I need to change sound in code.
Do someone know what is solution for it? Thanks.
CODE:
public void play() {
while(true) {
if (player == null) {
player = MediaPlayer.create(context, R.raw.zvuk);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlayer();
}
});
}
player.start();
}
}
public void stopPlayer() {
if (player != null) {
player.release();
player = null;
}
}
}
you are using infinite loop, which will never end. Replace your code with this:
public void play() {
if (player == null) {
player = MediaPlayer.create(context, R.raw.zvuk);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// play again or write your logic for repeat
play();
}
});
}
player.start();
}
public void stopPlayer() {
if (player != null) {
player.release();
player = null;
}
}

How can I make the music stop?

So I made a media Player that works fine but I have one big problem, after pressing play, if I close the activity or app, the music continues to play, if I click again, the music plays on the other one, and I don't know how to fix it. I just want the music to stop after closing the activity or app without any problem.
Here is the full code:
public class m1 extends AppCompatActivity {
ImageView backm1, replay, forward, btPlay, btPause;
TextView playerPosition, playerDuration;
CircularSeekBar seekBar;
MediaPlayer mediaPlayer;
Handler handler = new Handler();
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m1);
backm1 = (ImageView) findViewById(R.id.backm1);
backm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m1.super.onBackPressed();
}
});
playerPosition = findViewById(R.id.playerPosition);
playerDuration = findViewById(R.id.playerDuration);
replay = findViewById(R.id.replay);
forward = findViewById(R.id.forward);
seekBar = findViewById(R.id.seekBar);
btPause = findViewById(R.id.btPause);
btPlay = findViewById(R.id.btPlay);
mediaPlayer = MediaPlayer.create(this,R.raw.ding_dong);
runnable = new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(this,500);
}
};
int duration = mediaPlayer.getDuration();
String sDuration = convertFormat(duration);
playerDuration.setText(sDuration);
btPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btPlay.setVisibility(View.GONE);
btPause.setVisibility(View.VISIBLE);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
handler.postDelayed(runnable, 0);
}
});
btPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.pause();
handler.removeCallbacks(runnable);
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if(mediaPlayer.isPlaying() && duration != currentPosition){
currentPosition = currentPosition + 10000;
playerPosition.setText(convertFormat(currentPosition));
mediaPlayer.seekTo(currentPosition);
}
}
});
replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
if (mediaPlayer.isPlaying() && currentPosition > 10000){
currentPosition = currentPosition - 10000;
playerPosition.setText(convertFormat(currentPosition));
mediaPlayer.seekTo(currentPosition);
}
}
});
seekBar.setOnSeekBarChangeListener(new CircularSeekBar.OnCircularSeekBarChangeListener() {
#Override
public void onProgressChanged(CircularSeekBar circularSeekBar, float v, boolean b) {
if (b) {
mediaPlayer.seekTo((int) v);
}
playerPosition.setText(convertFormat(mediaPlayer.getCurrentPosition()));
}
#Override
public void onStopTrackingTouch(CircularSeekBar circularSeekBar) {
}
#Override
public void onStartTrackingTouch(CircularSeekBar circularSeekBar) {
}
});
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)));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer !=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
I added onDestroy but I think in a wrong way and this error came out:
2021-03-08 10:13:40.843 419-4716/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags: } when converting to stream
2021-03-08 10:13:40.906 28868-28868/com.example.diligent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.diligent, PID: 28868
java.lang.IllegalStateException
at android.media.MediaPlayer.getCurrentPosition(Native Method)
I added this:
private void stopPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
Toast.makeText(this, "MediaPlayer released", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
And the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
Any other suggestions are welcome.
Thank you in advance.
Stop and release media resources on onDestroy of activity.
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer !=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
MediaPlayer player; //MediaPlayer object
*Function to stop media Player *
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "MediaPlayer released", Toast.LENGTH_SHORT).show();
}
}
Call the function in onStop() callback
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}

How to make wait MediaPlayer for other hit requests?

There is a play button(sound review), when I hit it plays, but when I hit several times, it plays multiply.
I wanted to stop this with other topic's codes, didn't help, any idea?
img_scream1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaControl.isPlaying()==true){
mediaControl.pause();
}
else
{
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
mediaControl.start();
}
}
});
Change your code to something like this:
boolean isPaused = true;
img_scream1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isPaused){
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
mediaControl.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
}
});
mediaControl.start();
isPaused = false;
}
else
{
mediaControl.pause();
isPaused = true;
}
}
});
Don't create the mediaControl instance every time(Which makes the song to load from begining). Instead, you can initialise mediaControl to null and create an instance of it when it is null
mediaControl =null;
img_scream1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
if (mediaControl == null) {
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
}
if (mediaControl.isPlaying() == true) {
mediaControl.pause();
} else {
mediaControl.start();
}
}
});

Android: how to Play Mp3 sound as a notification?

I have a countdown that, when it is done, it invokes the following onFinish method:
public void onFinish() {
azanCountdownH1.setText("Get ready now");
}
In order to be able to play a mp3 file at the end of the countdown, I changed the onFinish method to:
public void onFinish() {
playNotification();
azanCountdownH1.setText("Get ready now");
}
Where playNotification looks exactly like:
public static void playNotification(){
MediaPlayer mp = MediaPlayer.create(MyApplicationContext.getAppContext(), R.raw.azan);
mp.start();
}
But it is not working !!
On Android Moniter on Android-Studio it is showing the following:
Any suugestion on what or where the bug might be ?!
the Context you pass to MediaPlayer.create() is null. I would suggest to pass the Context to your playNotification method:
public void onFinish() {
playNotification(this);
azanCountdownH1.setText("Get ready now");
}
public static void playNotification(Context context){
MediaPlayer mp = MediaPlayer.create(context, R.raw.azan);
mp.start();
}
You might be passing a wrong Context so just replace Activity.this with your Activity name
public static void playNotification(){
MediaPlayer mediaplayer = MediaPlayer.create(Activity.this, R.raw.azan);
if(mediaplayer == null) {
Log.v(TAG, "Create() on MediaPlayer failed.");
} else {
mediaplayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
mediaplayer.stop();
mediaplayer.release();
}
});
mediaplayer.start();
}
}
Try to this code hope this can help you..
public void onFinish() {
azanCountdownH1.setText("Get ready now");
playNotification(youractivity.this);
}
public void playNotification(Context context){
MediaPlayer mp = new MediaPlayer();
mp = MediaPlayer.create(context, R.raw.azan);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();
}

How to set duration of android mediaPlayer on start activity

I need help to set duration of MediaPlayer on start activity.
I have tried using seekTo() but its not working correctly.
Here is what I'm doing:
protected void Player(String bURL, int seekTo){
btn = (Button) findViewById(R.id.playpauseBtn);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(bURL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mediaPlayer.isPlaying()) {
if (seekTo != 0) {
mediaPlayer.seekTo(seekTo);
}
mediaPlayer.start();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Try to modify to this:
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying()) {
if (seekTo != 0) {
mp.seekTo(seekTo);
}
mp.start();
}
}
});
mediaPlayer.setDataSource(bURL);
mediaPlayer.prepareAsync();

Categories

Resources