Android MediaPlayer to show a progressdialog until the song is buffered - android

What i have: code that plays mp3 song from server. It is working correctly
What i am trying to do:
place a progress dialog until onPrepared() event is reached which is
not happening
I tried using progress dialog as we do in async task which is not
showing up.
Is there any other correct way to do this
This i am trying to do because UI hangs in case of low net connectivity, there is no problem in case of good connectivity
<------- Blah blah code---------->
..
..
..
play(<mp3url>);
public void play(String url) {
try {
//mediaPlayer.stop();
mediaPlayer.setDataSource(url);
if(pd.isShowing() && pd!=null){
pd.dismiss();
pd=null;
}
pd = new ProgressDialog(ActAtomicGodDetailTunesCategorySongs.this);
pd.setMessage("loading...");
pd.setCancelable(false);
pd.show();
mediaPlayer.prepare();
//mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//mediaPlayer.start();
//mediaPlayer.prepareAsync();
//seekBarProgress.postDelayed(onEverySecond, 1000);
}
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
duration = mediaPlayer.getDuration();
seekBarProgress.setMax(duration);
if(pd!=null && pd.isShowing()){
pd.dismiss();
}
mediaPlayer.start();
seekBarProgress.postDelayed(onEverySecond, 1000);
}
..
..
..
<------- Blah blah code---------->

You can use a text view(Text: Buffering) instead of using Progress Dialog.
public void playmusic(){
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
text_buffer= (TextView) findViewById(R.id.txt_buffer);
mediaPlayer.setDataSource(store);
text_buffer.setVisibility(View.VISIBLE);
//very important. you should do this prepareAsync();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
text_buffer.setVisibility(View.GONE);//or you can use View.INVISIBLE
mediaPlayer.start();
playState=true; // This is boolean to check whether music plays or not
}
});

Related

Adding delay while Mediaplayer loops

Playing .wav file using MediaPlayer class. As I need to loop the Audio I've set .setLooping(true); . So obviously, the doubt is how do I add a delay each time the audio plays, say I want a delay of 5000 .
The answers to similar questions here doesn't work in my case. Any help would be appreciated. Here is my code:
Button Sample = (Button)findViewById(R.id.samplex);
Sample.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filePath = Environment.getExternalStorageDirectory()+"/myAppCache/wakeUp.wav";
try {
mp.setDataSource(filePath);
mp.prepare();
mp.setLooping(true);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
You need to register 2 listeners (on completion and on error) and then you would need to delay next play in on completion callback. Reason for the error listener is to return true to avoid calling on completion event whenever there is an error - explanation here
private final Runnable loopingRunnable = new Runnable() {
#Override
public void run() {
if (mp != null) {
if (mp.isPlaying() {
mp.stop();
}
mp.start();
}
}
}
mp.setDataSource(filePath);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
button.postDelayed(loopingRunnable, 5000);
}
});
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
...
return true;
});
mp.prepare();
// no need to loop it since on completion event takes care of this
// mp.setLooping(true);
Whenever your destruction method is (Activity.onDestroyed(), Fragment.onDestroy(), View.onDetachedFromWindow()), ensure you are removing the runnable callbacks, e.g.
#Override
protected void onDestroy() {
super.onDestroy();
...
button.removeCallbacks(loopingRunnable);
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
}

Any way to speed up this code. Streaming audio Android

Making an app and streaming audio from site. I've got a menu and when I click the button to open the radio activity it can take from 8-20 seconds to load and sometimes force closes. Any help would be awesome thanks.
Code:
public class Radio extends Activity {
private MediaPlayer mp;
private ImageButton pauseicon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
getActionBar().setDisplayHomeAsUpEnabled(true);
/**
* Play button click event plays a song and changes button to pause
* image pauses a song and changes button to play image
* */
String res = "http://216.235.91.36/play?s=magic24point7&d=LIVE365&r=0&membername=&session=magic24point7:0&AuthType=NORMAL&app_id=live365%3ABROWSER&SaneID=24.79.96.172-13316781890137014897763&tag=live365";
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if (mp.isPlaying()) {
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if (mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (mp != null) {
if (mp.isPlaying())
mp.stop();
mp.release();
}
// there is no reason to call super.finish(); here
// call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
Use prepareAsync() and setOnPreparedListener() instead of prepare(). prepare() blocks the UI thread until it returns and is not recommended for a stream. This may be the cause your crash.
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
mp.start();
}
});
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
http://developer.android.com/reference/android/media/MediaPlayer.html#prepare()
Prepares the player for playback, synchronously. After setting the datasource and the display surface, you need to either call prepare() or prepareAsync(). For files, it is OK to call prepare(), which blocks until MediaPlayer is ready for playback.
Otherwise I think the network is your bottleneck. The fastest way to speed things up is to ensure your server/client communication is quick. There doesn't seem to be anything inherently slow about your code.

Android Playing MediaPlayer in SeparateThread

I have a Mp3Link need to play it on my Device in a Separate Thread
I have tried this,But when i execute my code ,I'm not able to play the Music,Could any one look at My Code,What Went Wrong?
Here My Code:
Thread trd = new Thread(new Runnable(){
public void run(){
//code to do the HTTP request
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(mp3Link);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
// You can show progress dialog here untill it prepared to play
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
// Now dismis progress dialog, Media palyer will start playing
Log.d("Mediaplyer>>>>>>>>", "Mediaplyer>>>>>>>>");
mp.start();
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// dissmiss progress bar here. It will come here when
// MediaPlayer
// is not able to play file. You can show error message to user
return false;
}
});
}
});
trd.start();
How about put
mediaPlayer.prepareAsync();
at the end of run() function ?
Thread trd = new Thread(new Runnable(){
public void run(){
//code to do the HTTP request
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(mp3Link);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// mediaPlayer.prepareAsync(); // <== Marked
// You can show progress dialog here untill it prepared to play
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
// Now dismis progress dialog, Media palyer will start playing
Log.d("Mediaplyer>>>>>>>>", "Mediaplyer>>>>>>>>");
mp.start();
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// dissmiss progress bar here. It will come here when
// MediaPlayer
// is not able to play file. You can show error message to user
return false;
}
});
mediaPlayer.prepareAsync(); // <== Add
}
});
trd.start();
Hope this helps.

Android: Playing multiple audio tracks

I am developing in Android and have been trying to create an Async task that plays audio files in order depending on a set of boolean values (if i1 is true, then it plays i1, and then when i1 is done, if i2 is true it plays that and so on). My first attempt is not crashing the app, but is also not playing the audio file.
class SessionMusicTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
try {
while(playing == true){
if(i1 == true && done == true){
done = false;
player.setDataSource(i1Loc);
player.prepare();
player.start();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
done = true;
}
});
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Is this the best approach to the problem? Any idea why the file isn't playing?
Thanks for any help in advance.
Update:
I just put a finish() in the onPostExecute() and the activity ends almost immediately, leading me to believe the task is not even starting to play the audio file?
Make sure you are releasing the MediaPlayer class when a song is done playing otherwise you could see some strange behavior:
mp.release();
Write following outside from :: doInBackground(Void... params) {
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
done = true;
}
});

Progress Bar while media player is preparing

I am trying to figure out how to have a progress bar that says "Loading. Please Wait..." while my media player prepares a streaming file. What occurs now is that it displays after the song is prepared. how can i fix this?
mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
/*dubstep stream*/
try {
dubstepMediaPlayer.setDataSource(dubstepPlaylistString[0]);
dubstepMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
dubstepMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dubstepMediaPlayer.start();
if(dubstepMediaPlayer.isPlaying()){
mediaPlayerLoadingBar.dismiss();
}`
EDIT:
This is the code I have now:
`switch(pSelection){
case 1:
new AsyncTask<Void, Void, Void>(){
#Override
protected void onPreExecute(){
mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
try {
dubstepMediaPlayer.setDataSource(dubstepPlaylistString[0]);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dubstepMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
return null;
}
protected void onPostExecute(Void result){
//mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true)
dubstepMediaPlayer.prepareAsync();
dubstepMediaPlayer.start();
mediaPlayerLoadingBar.dismiss();
}
}.execute();`
If someone Still facing this problem here is the code below
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
if(translation.equals("NIV"))
{
if(AudioPlaying==false)
{
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(Main.this);
mediaController = new MediaController(Main.this);
}
else
mediaController.show();
}
else
Toast.makeText(getBaseContext(), "عفوا, جاري تحميل ملفات الصوت الخاصة بترجمة الفانديك ", Toast.LENGTH_LONG).show();
pd = new ProgressDialog(Main.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
//Thread.sleep(5000);
try
{
mediaPlayer.setDataSource(AudioUrlPath);
mediaPlayer.prepare();
mediaPlayer.start();
AudioPlaying=true;
}
catch (IOException e) {
Log.e("AudioFileError", "Could not open file " + AudioUrlPath + " for playback.", e);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
//b.setEnabled(true);
}
}
};
task.execute((Void[])null);
The issue lies in that you are not doing anything asynchronously here, and you should be. You should use an AsyncTask to do your work.
Take a look at 'the 4 steps', as detailed here:
The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
EDIT:
You can create an anonymous inner class to do your bidding, which may be similar to how you are creating your onClick handler. In your onClick do something like this:
//pseudo-code...
onClick(View v, ...) {
new AsyncTask<Generic1, Generic2, Generic3>() {
protected void onPreExecute() {
// do pre execute stuff...
}
protected Generic3 doInBackground(Generic1... params) {
// do background stuff...
}
protected void onPostExecute(Generic3 result) {
// do post execute stuff...
}
}.execute();
}
Don't forget to keep an eye on your generics here!
Here is the activity class.Here i am showing the way only.
package com.android.mediaactivity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class MediaActivity extends Activity
{
public LinearLayout mainLayout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainLayout=(LinearLayout)findViewById(R.id.mainlinear);
MediaPlayer media=new MediaPlayer(this);
media.startPlayer();
}
}
Here is mediaplayerclass.
package com.android.mediaactivity;
import java.io.IOException;
import android.media.MediaPlayer.OnPreparedListener;
public class MediaPlayer implements OnPreparedListener {
MediaActivity mediaActivity;
android.media.MediaPlayer mediaPlayer;
public MediaPlayer(MediaActivity mediaActivity) {
this.mediaActivity = mediaActivity;
}
public void startPlayer() {
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.reset();
try {
mediaPlayer.setDataSource("");
mediaPlayer.prepareAsync();
toggleProgress(true);
} catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void onPrepared(android.media.MediaPlayer mp) { toggleProgress(false); mediaPlayer.start(); }
public void toggleProgress(final boolean show) {
mediaActivity.runOnUiThread(new Runnable() {
public void run() {
if (show) mediaActivity.mainLayout.setVisibility(mediaActivity.mainLayout.VISIBLE);
else mediaActivity.mainLayout.setVisibility(mediaActivity.mainLayout.INVISIBLE);
}
});
}
}
}
}
And here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/mainlinear"
android:visibility="invisible">
<ProgressBar android:id="#+id/ProgressBar01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>
When you say prepare on the underlying mediaplayer object, internally it really does some preparation like - setting up the extractor for the file, setting up the audio decoder to decode the encoded audio file and setting up the audio sink to play the raw audio data that was decoded from the decoder. Now all this will take time, it is not instantaneous.
So in your original code, you check if the mediaplayer isPlaying and then dismiss it but the problem is at that point of time the mediaplayer is not playing the audio yet and thus your dismiss is never called so it always visible.
What you need to do is implement the listener MediaPlayer.OnPreparedListener and when the method onPrepared is called in your application call the dismiss mediaPlayerLoadingBar.dismiss(); in that method.
Here is my solution :
The prepareAsync function used to prepare the audio and it is a non blocking operation (it is not blocking the main thread of the app).
Then I used the callback setOnPreparedListener to get notified when the
prepareAsync return, and the audio is ready
public void playAudio(String audioFile){
//init the progress dialog
final ProgressDialog progressDialog = new ProgressDialog(SubjectActivity.this);
try {
progressDialog.setCancelable(false);
progressDialog.setMessage(" Waiting to Prepare ...");
progressDialog.show();
// pass the url file to the media player
mediaplayer.setDataSource(audioFile);
mediaplayer.prepareAsync();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//the callback gets called when prepareAsync audio file become ready,
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaplayer.start();
// cancel the dialog
progressDialog.cancel();
}
});
}
Finally found out:
Guys very Imp point:
After setting url
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
I have added prepare_sync() and added handler cause it was crashing for big files
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mediaPlayer.prepareAsync();
ProgressDialog progressDialog = ProgressDialog.show(Player.this,
"Loading Title", "Loading Message");
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
});
// might take long! (for buffering, etc)
mediaPlayer.start();
}
},500);
This code will add progressbar too.
Points:
set url
prepareasync
OnPreparedlistener
Progressbar
mp.start-done
This is my way of doing btw I have heard there is alternative Exoplayer have a look at that too !

Categories

Resources