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();
Related
I am creating a simple app which can play music from a url. There is no forward or backward button.. Just play and the music will stream from url and will be played..
I need that control in notification when i click play button where in notification a close button also should be show to stop the music and clear the notification.
How could i implement it..
my Code in Music is
/** This method initialise all the views in project*/
private void initView() {
buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
#Override
public void onClick(View v) {
buttonPlayPause.setImageResource(R.drawable.button_pause);
if(v.getId() == R.id.ButtonTestPlayPause){
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource(audioUrl); // setup song from https://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();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.SeekBarTestPlay){
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if(mediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
buttonPlayPause.setImageResource(R.drawable.button_play);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
seekBarProgress.setSecondaryProgress(percent);
}
I'm testing Android sound implementation. I have an "imagenButton" and when I push it, a method "musica()" is called. Is really simple:
public void musica(View v) {
img = (ImageView) findViewById(R.id.Migrunido);
if(m.isPlaying()) {
m.stop();
}
else {
m.start();
}
}
It works, but want when I press the button, the sound repeats. I was reading a lot about threads and I have to prepare it before "stop()" but can't fix it.
I have to prepare my method? Or what is the problem?
Thanks
try
public static void playAudio(int id) {
mediaPlayer = MediaPlayer.create(context,id);
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.release();
}
});
}else{
mediaPlayer.stop();
mediaPlayer.release();
}
}
if this doesn't work try mediaPlayer.prepare(); before you start.
i am displaying images and video in imageview and videoview but the issue is when video is
playing onpreparedlistener called but when video finish oncompletion listener not called
when videoview complete i increment the i for next video or images
also it gives me error in logcat like this but video is playing
10-29 20:12:47.770: E/MediaPlayer(3975): error (1, -2147483648)
private void nextVideo(String path){
mImageview.setVisibility(View.GONE);
if(mVideoview.getVisibility()==View.GONE){
mVideoview.setVisibility(View.VISIBLE);
}
controller = new MediaController(HomeActivityNewViewPager.this);
mVideoview.setVideoURI(Uri.parse(path));
mVideoview.setMediaController(null);
controller.setMediaPlayer(mVideoview);
mVideoview.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mVideoview.start();
long duration = mVideoview.getDuration();
second=duration;
//handler.removeCallbacks(runnable);
//handler.postDelayed(runnable,second);
}
});
mVideoview.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.v("video view completed","---"+i);
mp.reset();
if(automode){
if(i==myplaylistlocal.size() || i>myplaylistlocal.size())
{
String checkcount=spreferences.getString("roundcount", "");
Log.v("roundcount==Before Integer.parseInt","---->"+roundcount);
if(roundcount>=Integer.parseInt(checkcount))
{
roundcount=0;
Log.v("roundcount==After Integer.parseInt","---->"+roundcount);
updateplaylist();
}
i=0;
indexplus();
imagesautomode();
i++;
}
else if(i==myplaylistlocal.size()-1)
{
imagesautomode();
i++;
}
else{
imagesautomode();
}
}
else{
i++;
images();
}
}
});
mVideoview.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.v("Error in video playing","----->"+i);
return true;
}
});
}
Either way, the error referenced above is MEDIA_ERROR_UNKNOWN. If this video was made for this app, I would make sure that it is properly encoded for Android. Also make sure that is clearly defines its endpoint.
http://developer.android.com/reference/android/media/MediaPlayer.html#MEDIA_ERROR_UNKNOWN
this is a work around but could possbly work in your situation:
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if(what == MediaPlayer.MEDIA_ERROR_UNKNOWN)
//ERROR UNKNOWN - COULD BE IMPROPERLY FORMATTED VIDEO {
//MOVE ON TO NEXT VIDEO
//DO LOGGING
}
}
I am working on audio streaming android application in this I get song url from server which i am playing using audio streaming application in this when I start playing it starts and it shows buffering also but my problem is when i move seekbar to particular position which is not buffered seekbar handle is moving back.actually I need to start playing song from that position.
see my code and please tell me how to handle this scenario
public class StreamingMp3Player extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
public EditText editTextSongURL;
private MediaPlayer mediaPlayer;
private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
private final Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
/** This method initialise all the views in project*/
private void initView() {
buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
editTextSongURL.setText("http://instilltech.netii.net/01LECHIPODAMA.mp3");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
#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();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.SeekBarTestPlay){
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if(mediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
buttonPlayPause.setImageResource(R.drawable.button_play);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
seekBarProgress.setSecondaryProgress(percent);
}
}
This is the code in my main Activity:
private void initControls()
{
streamButton = (Button) findViewById(R.id.button_stream);
streamButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
loading = (ProgressBar) findViewById(R.id.progressBar1);
Toast
.makeText(
MyActivity.this,
"The following stream is about to start" + station,
Toast.LENGTH_LONG).show();
player.playAudioFile(urlstring2);
streamButton.setEnabled(false);
notificate();
}
});
}
And here is the code in witch i start the mediaplayer itself:
public class player extends MyMainActivity{
static MediaPlayer player;
private static final String TAG = player.class.getSimpleName();
public static void playAudioFile(String urlstring2) {
player = new MediaPlayer();
try {
player.setDataSource(urlstring2);
loading.setVisibility(View.VISIBLE);
player.prepareAsync();
//player.start();
} catch (Throwable thr) {
Log.e(TAG, "could not play audio", thr);
loading.setVisibility(View.INVISIBLE);
}
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
loading.setVisibility(View.INVISIBLE);
}
});
}
public static void releasePlayer() {
if (player != null) {
// Player-Ressourcen freigeben
player.release();
player = null;
}
}
}
What I want to do is to show the progressBar (the cicling one) when the user presses the "play" Button, and I need it to disapear when the mediaplayer starts to play.
atm I just get the circle to show after the player has startet to play and never disapear ...
Edit: I got it to work.
I did initiate the player like this: player.prepare(); insteas of player.prepareAsync();
So the progressbar was shown for a view milliseconds.
Try this out.
Start the Progress Bar in the button click here like this,
streamButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
ProgressDialog progressDialog=null;
progressDialog=ProgressDialog.show(context, "", "Playing...");
Toast
.makeText(
MyActivity.this,
"The following stream is about to start" + station,
Toast.LENGTH_LONG).show();
player.playAudioFile(urlstring2);
streamButton.setEnabled(false);
notificate();
}
});
And you have to override the media player's on Prepared listener, so that you can stop the progress bar within it like this,
Player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
progressDialog.cancel();
}
});
By this you can achieve to show Progress until your Mediaplayer starts to play the file.
Came back to finally mark this Question as solved, so I copied what I edited into my question previously.
I got it to work. I did initiate the player like this:
player.prepare(); insteas of player.prepareAsync(); So the progressbar
was shown for a view milliseconds.
add the code to hide your ProgressBar after this line:
player.start();
And also in your catch block. That should make it go away once the player is either playing, or failing to play.
If you add the code that you are using to show the ProgressBar now I can help you with how to hide it also.