MediaPlayer freezing application in loop - java

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;
}
}

Related

Handling volume buttons with screen locked

Currently, I'm working on my simple android studio script, and I must use volume down while the mobile screen is locked.
Please, take a look at my script:
public class MainActivity extends AppCompatActivity {
public MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final BroadcastReceiver vReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
initAudio(getApplicationContext(), "https://www.w3schools.com/html/horse.mp3");
}
};
registerReceiver(vReceiver, new IntentFilter("android.media.VOLUME_CHANGED_ACTION"));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
event.startTracking();
initAudio(getApplicationContext(), "https://www.w3schools.com/html/horse.mp3");
return true;
}
return super.onKeyDown(keyCode, event);
}
public void initAudio(final Context context, String url) {
if (mediaPlayer == null) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
killMediaPlayer();
}
});
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Fail", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
}
}
public void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
What should I do to fix this issue? There are no errors, the script only works when I'm with my screen unlocked.
Can you help me with this?
Thank you very much.

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();
}

MediaPlayer continue playing only when specific activity starts

I have a Mediaplayer of background music for my activity. I want to pause it and reset it when new activity starts and stop it when the activity destroys.
I did it like that:
#Override
protected void onResume() {
if(!continiue){
continiue=true;
try{
if (m != null) {
m=new MediaPlayer();
m.reset();
m = MediaPlayer.create(this, R.raw.menu);
m.start();
m.setLooping(true);
}
else{
m.start();
}
}
catch(Exception e){
e.printStackTrace();
}
super.onResume();
}
}
#Override
protected void onStop() {
try{
if(m!=null){
m.stop();
m.release();
}
}
catch(Exception e){
}
super.onStop();
}
#Override
protected void onPause() {
try{
if(m.isPlaying()){
m.pause();
}
}
catch(Exception e){
}
super.onPause();
}
This worked fine. Now I want to add another activity but I want the music to continue playing only when this specific activity opens. How can I do that?
Create a separate class only for music playing and rule it from Activities. Something like this:
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
public class BackgroundMusicPlayer {
private static MediaPlayer mp = null;
private static int playingResId;
public static boolean isSoundTurnedOff;
private static boolean isPaused;
/** Stop old sound and start new one */
public static void play(Context context, int resIdToPlay) {
if (isSoundTurnedOff || context==null)
return;
if (mp != null && playingResId==resIdToPlay) {
if (isPaused)
mp.start();
isPaused = false;
return;
}
stop();
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
context.sendBroadcast(i);
playingResId = resIdToPlay;
mp = MediaPlayer.create(context, resIdToPlay);
if (mp != null) {
mp.setLooping(true);
mp.start();
} else
Log.e("BackgroundMusicPlayer","Cant create MediaPlayer. MediaPlayer.create(context: "+context+", resIdToPlay: "+resIdToPlay+") returns null");
}
/** Stop the music */
public static void stop() {
if (mp != null) {
isPaused = false;
playingResId = 0;
mp.stop();
mp.release();
mp = null;
}
}
public static void pause() {
if (mp != null){
mp.pause();
isPaused = true;
}
}
public static void resume() {
if (mp != null && isPaused){
mp.start();
isPaused = false;
}
}
}

Android: How to stop all active Media Players?

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.

Categories

Resources