Static MediaPlayer stops one second after loop for no reason - android

Today I added a static MediaPlayer to my Activity.
It is static so I can stop it from outside the class it is written in.
But for some reason the MediaPlayer stops after the second or third loop without an error in Logcat.
This is my code:
public static MediaPlayer player;
public static void SoundPlayer(Context ctx,int raw_id){
player = MediaPlayer.create(ctx, raw_id);
player.setLooping(true); // Set looping
player.setVolume(100, 100);
player.start();
}

setLooping after start()
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
player.setLooping(true); // Set after start()

Related

Android MediaPlayer plays sound with lower volume the first time

This is the code I'm using to create a notification sound. However, the media player plays the sound with a lower volume when the function is called for the first time. If this function is immediately called again, it then plays with the desired volume which is the stream volume.
Uri notification = RingtoneManager.getActualDefaultRingtoneUri(context,
RingtoneManager.TYPE_NOTIFICATION);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(context, notification);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.setOnPreparedListener(new
MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mMediaPlayer.setVolume(1, 1);
if(!mMediaPlayer.isPlaying())
mMediaPlayer.start();
}
});
mMediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mMediaPlayer.release();
}
});
mMediaPlayer.prepareAsync();
How to play the sound with the right volume at all times?

How to play a lot of sounds in background of an activity?

For example, I want to play 3 songs. When the 1st song ends, the 2nd song begins, and when the 2nd song ends, the 3rd song begins, and when the 3rd song ends, the 1st song begins again and so on. Is the mp.setOnCompletionListener used here?
You are right. You can do something simple like this:
public class MainActivity extends Activity {
MediaPlayer mp1, mp2, mp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp1 = MediaPlayer.create(this, R.raw.music_1);
mp2 = MediaPlayer.create(this, R.raw.music_2);
mp3 = MediaPlayer.create(this, R.raw.music_3);
mp1.start();
mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp2.start();
}
});
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp3.start();
}
});
mp3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp1.start();
}
});
}
}
This will play mp1 and onCompletion of it, it will play mp2, and onCompletion of mp2, it will play mp3, and onCompletion of mp3, it will play mp1 again and so on...
First declare the 3 MediaPlayer files:
MediaPlayer song1;
MediaPlayer song2;
MediaPlayer song3;
Then initialize the MediaPlayer objects:
song1 = MediaPlayer.create(this, R.raw.exampleSong1);
song2 = MediaPlayer.create(this, R.raw.exampleSong2);
song3 = MediaPlayer.create(this, R.raw.exampleSong3);
Now start the first Media file with
song1.start();
Now with every instance created you should add to every MediaPlayer object a setOnCompletionListener like this:
song1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
song2.start();
}
});
Do the same for the Second and Third MediaPlayer files:
song2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
song3.start();
}
});
song3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
song1.start();
}
});

setNextMediaPlayer not working

I am trying to find out how to use the android's MediaPlayer method setNextMediaPlayer which should smoothly transition from one player (song) to another. But do not know how to use the method since there is a lack of documentation.
This is what i do and it does not work:
final MediaPlayer mp1 = new MediaPlayer();
final MediaPlayer mp2 = new MediaPlayer();
try {
mp1.setDataSource("http://song1.MP3");
mp2.setDataSource("http://song2.mp3");
mp1.prepareAsync();
mp1.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp1.start();
}
});
mp1.setNextMediaPlayer(mp2);
mp1.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp2.prepareAsync();
mp2.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp2.start();
}
});
}
});
} catch (IllegalArgumentException e) {}
So the first song plays. But after it finishes the second does not start.
Got it to work.
mp1.setDataSource(song1);
mp1.prepareAsync();
mp1.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp1.start();
}
});
//mp1.start();
//mp1.seekTo(1000*100);
mp2.setDataSource(song2);
mp2.prepare();
mp1.setNextMediaPlayer(mp2);
The only problem is that the second mediaplayer cannot be called as async (i.e. mp2.prepareAsync()). I do not know why, but if you try it like that it does not start, which is a bad thing :/.
MediaPlayer setNextMediaPlayer gives a lot of problem what i do is this:
in the onCompletion() reset() the mediaplayer, setDataSource() and prepareAsync().
Something like this
mp1.setDataSource("http://song1.MP3");
mp1.prepareAsync();
mp1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp1.start();
}
});
mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp1.reset();
//ADD FLAG FOR STOP
try {
mp1.setDataSource("http://song2.mp3");
} catch (IOException e) {
e.printStackTrace();
}
mp1.prepareAsync();
}
});
Then in the onCompletion you need some flag to check if the last song was played to stop, because the code as i posted will loop in the last song.

Play Sound File from res/raw using MediaPlayer

I want to play Sound Files from raw folder using MediaPlayer but I don't want to use MediaPlayer.create() method, since I want to play it multiple times and want to retain MediaPlayer object. I was successful in compiling the following code but it plays nothing and I can't hear any sound.
public void STARTSOUND(SOUND sound) throws IOException {
switch(sound) {
case SOUND_MENUBG:
Uri uri = Uri.parse("R.raw.mainmenu");
PLAYSOUND(uri);
break;
}
}
public void PLAYSOUND(Uri file) throws IOException {
mPlayerLoopSound.setDataSource(GameManager.getInstance().getCurrentActivity(),file);
mPlayerLoopSound.prepareAsync();
mPlayerLoopSound.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mPlayerLoopSound.isPlaying()){
mPlayerLoopSound.setVolume(1.0f, 1.0f);
//start the player
mPlayerLoopSound.start();
}
}
});
}
The onPrepared() method never gets called..
Am I doing anything wrong?
private void playButtonSound(final Context context, final int resourceId)
{
final MediaPlayer mediaPlayer = MediaPlayer.create(context, resourceId);
if (mediaPlayer != null)
{
mediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mediaPlayer)
{
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
});
mediaPlayer.start();
}
}
Call this method like this.
playButtonSound(PopScreenActivity.this, R.raw.soundfilename);
First, hopefully you're initializing your MediaPlayer with:
mPlayerLoopSound = new MediaPlayer();
Next, make sure you call:
mPlayerLoopSound.setAudioStreamType(AudioManager.STREAM_MUSIC);
which:
Sets the audio stream type for this MediaPlayer. See AudioManager for a list of stream types. Must call this method before prepare() or prepareAsync() in order for the target stream type to become effective thereafter.
Then, in your OnPreparedListener(), when onPrepared() is called, notice the parameter it has: MediaPlayer mp. This is the MediaPlayer that is ready for playback, so you can use it:
#Override
public void onPrepared(MediaPlayer mp) {
if(!mp.isPlaying()) {
mp.setVolume(1.0f, 1.0f);
mp.start();
}
}

Not able to show spinner until mediaplayer is prepared

I tried various approaches but nothing is solving my problem. Hope someone here can help me.
Simple requirement is I want to show a spinner until media player window is shown. It sounds easy enough but it is not.
I am calling my mediaplayer class on "Listen" click of alertDialog. Here it is:
alertBox.setCancelable(false)
.setNegativeButton("Listen", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
dialog.dismiss();
emp = new EasyMediaPlayer(mp3PopupLayout,buttonPlayPause,seekBarProgress,tv_mp3,downloadURL);
emp.startPlayingMP3();
}
}).show();
And startPlaying function calls chooseToStart(true) which in-turn runs the media player. This class is:
public class EasyMediaPlayer implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
EasyMediaPlayer(View mp3PopupLayout,ImageView buttonPlayPause,SeekBar seekBarProgress,TextView tv_mp3, String MP3URL){
this.mp3PopupLayout = mp3PopupLayout;
this.buttonPlayPause = buttonPlayPause;
this.seekBarProgress = seekBarProgress;
this.tv_mp3 = tv_mp3;
this.MP3URL = MP3URL;
seekBarProgress.setOnTouchListener(this);
buttonPlayPause.setOnClickListener(this);
}
public void startPlayingMP3(){
mediaFileLengthInMilliseconds = 1;
tv_mp3.setText("");
buttonPlayPause.setImageResource(R.drawable.button_play);
buttonPlayPause.setVisibility(View.GONE);
seekBarProgress.setProgress(0);
seekBarProgress.setSecondaryProgress(0);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
tv_mp3.setText("Error in playing file !!");
return true;
}
});
mp3DownloadWindow = new PopupWindow(mp3PopupLayout, LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT, true);
mp3DownloadWindow.showAtLocation(mp3PopupLayout, Gravity.BOTTOM, 30, 0);
chooseToStart(true);
}
public void chooseToStart(boolean startFlag){
if(startFlag){
try {
mediaPlayer.setDataSource(this.MP3URL);
mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
} catch (Exception e) {
tv_mp3.setText(e.toString() + "\nClose it");
}
if(!mediaPlayer.isPlaying()){
spinner.cancel();
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.button_pause);
}else {
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.button_play);
}
primarySeekBarProgressUpdater();
}
}
//other stuff
}
I need to know where and how I can use spinner so it will be shown until media player starts playing.
Any help will be appreciated. Thanks
Use prepareAsync() and setOnPreparedListener() instead of prepare().
mediaPlayer.setDataSource(this.MP3URL);
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// Hide whatever you need, mediaPlayer is prepared
mp.start();
}
});
// Show whatever you need, mediaPlayer is preparing
mediaPlayer.prepareAsync();

Categories

Resources