Mediaplayer is playing random songs - android

Im using the following code to play music.
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.reset();
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.prepareAsync();
} else {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.prepareAsync();
}
Explanation:
when the user clicks a song for the first time, else loop will be
executed.
If the user clicks a song when the mediaplayer is playing a song already, if loop will
be executed
In my if loop, Im resetting the mediaplayer before setting the data source so it calls the onCompletion listener.
Follwing is my onCompletionListener.
mMediaPlayer.setOnCompletionListener(mp -> {
MainActivity.nextTrackController.performClick();
});
Following is my nextTrackController onClickListener.
MainActivity.nextTrackController.setOnClickListener(v -> {
try {
if (MainActivity.currentOffset < (MainActivity.localTrackList.size() - 1)) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
} else {
mMediaPlayer.reset();
}
MainActivity.currentOffset = MainActivity.currentOffset + 1;
mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
mMediaPlayer.prepareAsync();
} else {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
}
MainActivity.currentOffset = 0;
mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
mMediaPlayer.prepareAsync();
}
} catch (Exception ex) {
}
});
the problem is that,
If the media player is playing and if the user is clicking a song, it is not playing the specific song that had been clicked but it plays some random song.
If the song finished playing, it plays a random song instead of the next song. How can i be able to sort this out?

Related

NullPointerException in MediaPlayer after pressing the home button and reopening the app

This is my code, I want to keep music playing when the app is in background. And I want to be able to pause it when I re-open the app. The music should play in the background, but for some reason media player returns null pointer when I re-open it. So, when I pause it, it crashes.
public void play(View view) {
if (status) {
status = false;
requestRecordAudioPermission();//audio permission
startPlay();//start mediaplayer
} else {
status = true;
mediaPlayer.pause();
}
}
public void startPlay() {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(URL_LINK);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(HomeActivity.this, "CAN'T PLAY!",Toast.LENGTH_LONG).show();
}
mediaPlayer.start();
}
Why Media Player returns null after pressing the home button and reopening the app?
Thanks for help
If you are streaming audio from an url then try to load the Media Player asynchronously.
String url = "YOUR_URL";
MediaPlayer myMediaPlayer = new MediaPlayer();
myMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
myMediaPlayer.setDataSource(url);
myMediaPlayer.prepareAsync();
} catch (IOException e) {
Toast.makeText(this, "mp3 not found", Toast.LENGTH_SHORT).show();
}
myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});

Prevent mediaplayer from calling onCompletionListener

I'm using the following code to play music when an user selects a song from the listview.
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.reset();
try {
mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.prepareAsync();
} else {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.prepareAsync();
}
mMediaPlayer.reset(); is calling the onCompletionListener. In my oncompletionListener, I'm playing the next song and hence instead of playing the selected song, it plays the next song in the listview. Is there by any ways I can prevent calling onCompletionListener and play only the song that's selected from listview?
You could do something like this.
boolean isMediaPlayerReset = false;
MediaPlayer mMediaPlayer = null;
//on list item click
if(mMediaPlayer.isPlaying()){
isMediaPlayerReset = true;
mMediaPlayer.reset();
try {
mMediaPlayer.setDataSource("/path");
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.prepareAsync();
}
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(isMediaPlayerReset){
isMediaPlayerReset = false;
return;
}
//play next song
}
});

MediaPlayer skips files if previous music file is short in length

I have a music service class in which I have a method called playNext().
public void playNext() {
setSong(songPosn + 1);
playSong();
}
and the playSong() method is,
public void playSong() {
if(player != null){
if(player.isPlaying()){
player.stop();
}
}
//play a song
isPaused = false;
isComplete = false;
isPrepared = false;
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
//get song
Song playSong = songs.get(songPosn);
//get id
long currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is when a song is played which has a very short length, player skips more than 1 song in the songs list. Even though, only 1 is incremented in the playNext() method.
Note: It doesn't happen every time. But most of the time. I cannot figure out the problem. And that short music file is a Facebook pop up sound which is less than 0 second in duration.

Multiple instance of media player issue in android

I am working with MediaPlayer in Android. I have all the list of songs name and URLs of songs from server. when I click on any item a song from server is played in MediaPlayer. Here is my code for playing song on click of "Listview" item.
txtEndTimingForMediaPlayer.setText("");
txtStarTimingForMediaPlayer.setText("");
seekBarPlayer.setProgress(0);
// this code is for stop current playing song and release media player
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer=null;
}
// start new song for play
mediaPlayer=new MediaPlayer();
Uri myUri1 = Uri.parse(url);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(getActivity(), myUri1);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
playPause=true;
player.start();
mediaFileLengthInMilliseconds = player.getDuration();
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playPause=false;
btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Now issue with this code is when I click continuously on song, then same song plays multiple time. how to avoid this multiple instance issue.
I think if(mediaPlayer!=null && mediaPlayer.isPlaying()) is not true when you click too fast to play same song and then mediaPlayer=new MediaPlayer(); is creating new instance and play song, which will result in hearing same song multiple times. debug and check if code enter that if (condition)

Android Mediaplayer Won't Stop

I have the following code to play an mp3 file from the web and this is working but when I use the stop functionality the audio does not stop. Can anyone point me towards a resource to find out more about this or tell me where I am going wrong? Thanks.
showAudio.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (!showAudio.getText().equals("Stop")) {
try {
String url = lblAudio.getText().toString();
if (url.length() > 2) {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
showAudio.setText("Stop");
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Sorry, there was a problem playing audio.", Toast.LENGTH_SHORT).show();
}
} else {
try {
mediaPlayer.stop();
mediaPlayer.release();
} catch (Exception ex) {
ex.printStackTrace();
}
showAudio.setText("Audio");
}
}
});
You are creating a new MediaPlayer every time you click the button. Create the player outside of the click handler.
Try out :
try {
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
}
} catch(Exception ex) {
ex.printStackTrace();
}
Try making your media player a global variable and make it static....
I have a working media player that starts and stops
Uri ringtone;
MediaPlayer mp;
ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mp = MediaPlayer.create(getApplicationContext(), ringtone);
//code to start the mediaplayer
if (Flags.notificationReceived) {
showAlert(Flags.patientModel);
Flags.notificationReceived = false;
mp.start();
mp.setLooping(true);
vibrate(2000);
}
//code to stop the media player
if (mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = MediaPlayer.create(getApplicationContext(), ringtone);
}

Categories

Resources