Android media player delay in prepare() - android

I have my code which plays music from the internet. My problem is it has a few delay and causes lag after clicking the button.
I have tried to use the prepareAsync() but no luck. Can anyone please let me know the issue.
#Override
public void onClick(View v) {
if (v.getId() == R.id.ButtonTestPlayPause) {
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource(editTextSongURL.getText().toString()); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
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.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.button_pause);
} else {
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.button_play);
}
primarySeekBarProgressUpdater();
}
}

Related

Adding controls like pause and play to media player

I have been able to play audio from my firebase storage and i want the song to stop and start when a user clicks on same button but i haven't been able to get get the right code for that.
this is what i have tried
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}else {
mediaPlayer.stop();
}
}
});
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
The above code is correct, now do one thing create button listener and write below code
button.setOnClickListener(view.onCLickListeners(){
#override
public void onClick(){
if (!mediaPlayer.isPlaying()) {
mediaPlayer.play();
}
else {
mediaPlayer.pause();
}
}});
And please define mediaplayer globally.

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

How can I know if the MediaPlayer is in Stopped state?

I am building an app which plays several videos, and I have two different user scenarios :
Scenario 1. While video 'A' is playing, if user clicks next button, then it stops and play the next video 'B'.
Scenario 2. Play video 'A', and if it's done, user clicks next button and it plays video 'B'.
For the first scenario, I used mediaPlayer.isPlaying() method to detect if it is in Started state and it works fine. However, if I use the same code for the second scenario, isPlaying() throws IllegalStateException.
Here's my code for playing videos :
private void playVideos(SurfaceHolder holder) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(holder);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + video_files[mCounter]);
mediaPlayer.setDataSource(this, uri);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (mCounter <= 8) {
onVideoCompletion(mediaPlayer);
} else {
mediaPlayer.stop();
mediaPlayer.release();
}
}
});
} catch (IOException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalStateException e) {
}
}
Also, here's my button listener to play next video :
nextBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
mCounter += 1;
if (mCounter <= 8) {
playVideos(holder);
}
}
});
One way that I tried to hack this issue was using a boolean variable instead of isPlaying() method. For example,
boolean mIsPlaying = false;
...
// in button listener
if(mIsPlaying) {
mediaPlayer.stop();
mediaPlayer.release();
}
...
// in playVideos() function
mediaPlayer.start();
mIsPlaying = true;
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (mCounter <= 8) {
onVideoCompletion(mediaPlayer);
} else {
mediaPlayer.stop();
mediaPlayer.release();
}
}
});
That works for my both of scenario, but I'm not sure if it's the correct way to do it. Isn't there any way to detect whether mediaPlayer is in Stopped state?
I took a look at Google's Documentation which you can find here. You can only know if the player isPlaying(); or isLooping(); ... So no, there is not an "easy" or "short" way to achieve what you want. Hope it helped.

How to play stream again after stop it in android?

I make one app in android, my problem is that when i play the stream it is playing well but when i click on stop button and then click on play button then song is not playing, how to do that ? please help me if anybody know. below is code that i write :-
// method for play stream after stop it.
public void startradio(View v) {
try{
if(mp.isPlaying()){
return;
}
mp.start();
} catch(IllegalStateException ex){
ex.printStackTrace();
}
}
// method for stop stream.
public void stopradio(View v) {
if(mp.isPlaying()){
mp.stop();
}
mp.release();
}
#Eluvatar's comment is pretty close but no cigar.
If you do that, your app still would be in the wrong state, and would need to call prepare() before calling start() again. You should look at the event cycle for MediaPlayer.
In other words a possible change would be
// method for play stream after stop it.
public void startradio(View v) {
try{
if(mp.isPlaying()){
return;
}
mp.prepare();
mp.start();
} catch(IllegalStateException ex){
ex.printStackTrace();
}
}
// method for stop stream.
public void stopradio(View v) {
if(mp.isPlaying()){
mp.stop();
}
}

Mediaplayer plays twice

I have a media player but when another file is selected it continues to play the old file and new one so it is playing two files at once here is my onCreate method
private MediaPlayer mediaplayer = new MediaPlayer();
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.songplaying);
// Getting Our Extras From Intent
Bundle names = getIntent().getExtras();
// Getting Specific Data
path = names.getString("pathkeyword");
//Start Player
try {
playAudio(path);
} catch (Exception e) {
e.printStackTrace();
}
and this is the method that plays the audio
private void playAudio(String url) throws Exception{
mediaplayer.release();
mediaplayer.setDataSource(url);
mediaplayer.prepare();
mediaplayer.start();
When you are start to play the song ,check it is playing or not and stop it if it is currently playing.
if(player.isPlaying())
{
mediaplayer.stop();
}
mediaplayer.reset();
mediaplayer.setDataSource(url);
mediaplayer.prepare();
mediaplayer.start();
no need to release the player.player.release() used only when player no longer needed .
And you have to use stop() and release() methods whenever activity destroys.Otherwise so many players are running in background.
Try to add this to oncreate method so you will be able to prevent the new creation of audio
Mediaplayer M = Mediaplayer.create(this,R.row.audio file)
and make a new function like
void my function {
// call it here
m.start();
}

Categories

Resources