I have some problems with my Mediaplayer. It works well, but at some mysterious circumstances it stops playing. So i put some logs in onCompletion and onError callbacks and surround it with try/catch, but when it stops none of thees logs are triggering. So my question is how can Mediaplayer stops playing and dont trigger this logs.
P.S. it plays in service, but i checked - service continue running, and also i tried to play it in singleton class and GCMService too - it still stops and i can't figure out why.
Here is my code.
public class AlertService extends Service {
private boolean isPlaying = false;
private MediaPlayer mp;
private final String TAG = "Alert_playing";
public static final String PLAY_ALERT_ACTION = "play_alert_service";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent!=null&&intent.getAction().equals(PLAY_ALERT_ACTION)){
playAlertSound();
}
return START_NOT_STICKY;
}
public void playAlertSound() {
if (!isPlaying) {
isPlaying = true;
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
mp = new MediaPlayer();
Uri ringtone = Uri.parse("android.resource://" + RetailerApplication.getAppContext().getPackageName() + "/" + R.raw.alert);
try {
mp.setDataSource(RetailerApplication.getAppContext(), ringtone);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
isPlaying = false;
stopSelf();
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
}
});
}
});
mp.prepareAsync();
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
isPlaying = false;
stopSelf();
Log.d(TAG, "what: " + what + " extra: " + extra);
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
return false;
}
});
} catch (IOException e) {
isPlaying = false;
stopSelf();
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
Log.d(TAG, "exception" + e);
Logger.e(TAG, e);
}
} else {
Log.d(TAG, "miss");
}
}
}
Related
i have shared a valid mp3 file in my google drive however I am not able to play it due to
E/MediaPlayer: Error (1,-1015)
I cannot find any documentation for this error
my link :"https://drive.google.com/file/d/1m_TKhtlPRBzBEencnU5-RITxheXm4x6q/view?usp=sharing"
my music service:
enter code here
package com.example.mpservice;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
public class PlayService extends Service implements
MediaPlayer.OnCompletionListener,MediaPlayer.OnPreparedListener
,MediaPlayer.OnSeekCompleteListener,MediaPlayer.OnInfoListener,
MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnErrorListener {
MediaPlayer mediaPlayer;
public final String TAG="MyService";
#Override
public void onCreate() {
Log.d(TAG,"playService start");
mediaPlayer=new MediaPlayer();
//mediaPlayer=MediaPlayer.create(this,R.raw.summer);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.reset();
super.onCreate();
Log.d(TAG,"onCreate Finish");
}
#Override
public int onStartCommand(Intent intent,int flags, int startId) {
Log.d(TAG, "onStartCommand");
String url = intent.getStringExtra("URL");
Log.d(TAG, "URL :" + url);
// Uri myUri = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.summer);
// Uri myUri = Uri.parse(url);
//Log.d(TAG ,"URI: " +myUri);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
Log.d(TAG, "data source" + e);
e.printStackTrace();
}
try {
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.d(TAG,"prepare :" + e);
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
if(( mediaPlayer !=null)&& mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
Log.d(TAG, "media player stoped " );
}
Log.d(TAG, "on Destroy " );
Log.d(TAG, "media lpayer :"+mediaPlayer );
super.onDestroy();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d(TAG, "error media player " + what +extra);
return false;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
Log.d(TAG, "info media player " + what +extra);
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "mp start ");
mp.start();
}
#Override
public void onSeekComplete(MediaPlayer mp) {
}
}
I am building a simple music app.
Regardless of what I try, I can not get a song to stop in order to play a new song. I tried stop, release, stop, and release together; I created a service; I even tried to use current position to get the position of the MP3 and consider it playing if the position is > 1.
But nothing worked and I am going mad trying to figure this out.
I worked on this for 5 days and have failed at everything I have thrown at it.
I would greatly appreciate any advice and a clear solution.
I am a noob and I am trying very hard to solve my own problems but this one just has me stumped.
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.IOException;
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer mediaplayer;
mediaplayer = new MediaPlayer();
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
String extRec = intent.getExtras().getString("extRec");
Log.d("My Service", "Received extra: " + extRec);
if (mediaplayer.isPlaying()){
Log.d("My Service is playing ", "yes");
}
else {
Log.d("My Service is playing ", "no");
}
//mediaplayer.stop();
//mediaplayer.release();
try {
final String AudioURL = extRec;
Log.d("My Service audioURL ", AudioURL);
mediaplayer.setDataSource(AudioURL);
mediaplayer.prepare();
Log.d("My Service", "position: " + mediaplayer.getCurrentPosition() );
mediaplayer.start();
} 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();
}
return START_STICKY;
}
}
User Media Controller will help you:
public class AudioPlayer extends Activity implements OnPreparedListener, MediaController.MediaPlayerControl{
private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
audioFile = this.getIntent().getStringExtra(AUDIO_FILE_NAME);
((TextView)findViewById(R.id.now_playing_text)).setText(audioFile);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(audioFile);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + audioFile + " for playback.", e);
}
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//the MediaController will hide after 3 seconds - tap the screen to make it appear again
mediaController.show();
return false;
}
//--MediaPlayerControl methods----------------------------------------------------
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
//--------------------------------------------------------------------------------
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
}
For good playing feature use Exoplayer
Im implemented my music player function and sometimes the ogg files throws the (1,-1010) thats means
MEDIA_ERROR_UNKNOWN/ MEDIA_ERROR_MALFORMED
error. There is nothing wrong with file format because sometimes the file loading correcly (lets say 70% correcly 30% got that error).
private void loadAudio(){
if(!readyToPlay){
elapsedTimeStart.setText("");
elapsedTimeEnd.setText(context.getString(R.string.loading));
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaplayer.setDataSource(audioURL);
mediaplayer.prepareAsync();
mediaplayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
double ratio = percent / 1000.0;
bufferingLevel = (int)(mp.getDuration() * ratio);
seekBar.setSecondaryProgress(bufferingLevel/SECOND);
}
});
mediaplayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.i("lang","on error " +what +" extra "+ extra);
switch (what) {
case MEDIA_ERROR_UNKNOWN:
Log.i(TAG, "MEDIA_ERROR_UNKNOWN");
break;
case MEDIA_ERROR_SERVER_DIED:
Log.i(TAG, "MEDIA_ERROR_SERVER_DIED");
Toast.makeText(context, context.getString(R.string.problems_connecting_try_again), Toast.LENGTH_SHORT).show();
break;
}
switch (extra) {
case MEDIA_ERROR_IO:
Log.i(TAG, "MEDIA_ERROR_IO");
break;
case MEDIA_ERROR_MALFORMED:
Log.i(TAG, "MEDIA_ERROR_MALFORMED");
break;
case MEDIA_ERROR_UNSUPPORTED:
Log.i(TAG, "MEDIA_ERROR_UNSUPPORTED");
break;
case MEDIA_ERROR_TIMED_OUT:
Log.i(TAG, "MEDIA_ERROR_TIMED_OUT");
Toast.makeText(context, context.getString(R.string.problems_connecting_try_again), Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.i("lang", " SUCCEFULLY PREPARED");
readyToPlay = true;
durationTime = mp.getDuration();
durationHour = durationTime /HOUR;
durationMint = (durationTime %HOUR)/MINUTE;
durationSec = (durationTime %MINUTE)/SECOND;
elapsedTimeStart.setText(String.format("%02d:%02d:%02d",currentHour,currentMin,currentSec));
elapsedTimeEnd.setText(String.format("%02d:%02d:%02d", durationHour, durationMint, durationSec));
seekBar.setMax(durationTime /SECOND);
play();
}
});
} catch (IllegalArgumentException|SecurityException|IllegalStateException|IOException e) {
Log.i("lang","Exception!");
e.printStackTrace();
}
catch (Exception e){
Log.i("lang", "Exception!! smthing goes wrong ");
e.printStackTrace();
}
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaplayer != null && fromUser) {
timeElapsed = durationTime * progress / 100;
mediaplayer.seekTo(timeElapsed);
if (durationTime / SECOND == timeElapsed / SECOND)
stop();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}}
EDIT: I debug my program and the first callback which trigger after mediaplayer.prepareAsync() is onPrepared method. Is there a way to check when the (MEDIA_ERROR_UNKNOWN/ MEDIA_ERROR_MALFORMED) occurs on this state and recall loadAudio() function to get correct track?
There is problem with URL, the URL is incorrect or the server not sending proper response by this URL.
Thats why this URL give this Error MEDIA_ERROR_MALFORMED
EDIT
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
LogUtils.e(TAG, "onError() called : what=="+what);
LogUtils.e(TAG, "onError() called : extra=="+extra);
return false;
}
});
I use media player in service and activity with a button(play/stop stream).
I'm trying to do such a one thing:
start serice only once when activity starts, and than use UI part to operate with media player in service (start, stop streaming). I'm using for it Service Binder.
But when i click on button to start media player, it causes errors:
E/MediaPlayer: start called in state 1
E/MediaPlayer: error (-38, 0)
Than i added the flag isPrepared to onPrepared() and on play stream button click check the flag. Flag is always false.
It seems that onPrepare() is not called or smth like that. Why? What's wrong?
UPDATED
Activity:
public class MainActivity extends AppCompatActivity {
String url = "http://62.80.190.246:8000/ProstoRadiO128";
Button mPlayPauseButton;
boolean musicPlaying = false;
Intent serviceIntent;
MyService mService;
boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
initListeners();
}
#Override
protected void onStart() {
super.onStart();
serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra("url", url);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
startService(serviceIntent);
musicPlaying = true;
mPlayPauseButton.setBackgroundResource(R.drawable.pause);
Log.d("", "mConnection: " + mConnection);
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyServiceBinder binder = (MyService.MyServiceBinder) service;
mService = binder.getService();
mBound = true;
Log.d("", "in onServiceConnected: mBound = " + mBound);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
private void initViews() {
mPlayPauseButton = (Button) findViewById(R.id.btn_play_pause);
mPlayPauseButton.setBackgroundResource(R.drawable.play);
}
private void initListeners() {
mPlayPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playPauseClick();
}
});
}
private void playPauseClick() {
if (musicPlaying == false) { //mBound &&
Log.d("", "mBound: " + mBound);
mService.startStream();
mPlayPauseButton.setBackgroundResource(R.drawable.pause);
musicPlaying = true;
}
else if (musicPlaying == true) { //!mBound
mService.stopStream();
mPlayPauseButton.setBackgroundResource(R.drawable.play);
musicPlaying = false;
}
}
}
UPDATED
Service:
public class MyService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener{
String TAG = "PlayerService__Log";
String url;
MediaPlayer mediaPlayer;
private final IBinder mBinder = new MyServiceBinder();
boolean isPrepared;
public class MyServiceBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
Log.v(TAG, "Creating Service");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
url = intent.getStringExtra("url");
Log.d(TAG, "url: " + url);
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, e.getClass().getName() + " " + e.getMessage());
}
}
return START_STICKY;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
Log.d(TAG, "media player prepared");
isPrepared = true;
}
#Override
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "onCompletion");
}
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
public void startStream() {
if (!mediaPlayer.isPlaying() ) { //&& isPrepared == true
mediaPlayer.start();
Log.d(TAG, "media player started");
}
else {
Log.d(TAG, "media player is not prepared");
//isPrepared = false;
}
}
public void stopStream() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
Log.d(TAG, "media player stoped");
}
}
}
You forgot to start the service. Call:
startService(serviceIntent);
Please read this as you will need to stop the service too.
and for pausing, rather than stop, call:
mediaPlayer.pause();
Familiarise yourself with the state diagram and invalid states in the docs.
onPrepared() is called when the player is successfully prepared/initialised.
But as the Error is indicating, something goes wrong during this phase and (probably) therfore onPrepared never gets called.
You could try to override onError, to get notified like this:
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int why) {
Log.e(TAG, "onError");
setPlayerState(PlayerState.ERROR);
if (MediaPlayer.MEDIA_ERROR_UNKNOWN == what) {
Log.d(TAG, "MEDIA_ERROR_UNKNOWN");
if (MediaPlayer.MEDIA_ERROR_IO == why) {
Log.e(TAG, "MEDIA_ERROR_IO");
if (this.playbackPosition > 0) { //we could play this video in the past, but cannot resume. start all over again.
Log.e(TAG, "Probably we requested a content range, but server didn't support that. (responded with 200), restarting!");
this.playbackPosition = 0;
start(this.playbackPosition);
} else {
callbacks.onUnrecoverableError(what, why);
}
}
if (MediaPlayer.MEDIA_ERROR_MALFORMED == why) {
Log.e(TAG, "MEDIA_ERROR_MALFORMED");
callbacks.onUnrecoverableError(what, why);
}
if (MediaPlayer.MEDIA_ERROR_UNSUPPORTED == why) {
Log.e(TAG, "MEDIA_ERROR_UNSUPPORTED");
callbacks.onUnrecoverableError(what, why);
}
if (MediaPlayer.MEDIA_ERROR_TIMED_OUT == why) {
Log.e(TAG, "MEDIA_ERROR_TIMED_OUT");
callbacks.onUnrecoverableError(what, why);
}
} else if (MediaPlayer.MEDIA_ERROR_SERVER_DIED == what) {
Log.e(TAG, "MEDIA_ERROR_SERVER_DIED");
callbacks.onUnrecoverableError(what, why);
}
return true;
}
I am plying all sounds from raw folder. Using playSound() and releasing sound after completion as well on error releasing sound. Still i am getting error(-19,0) after couple of sounds played using playSound().
public static MediaPlayer mediaPlayer;
public static boolean playSound(final Context context, int resId) {
if(releaseSound()){
mediaPlayer = MediaPlayer.create(context, resId);
mediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d("test", "Media player error :" + what + " extra:" + extra);
if(what == 19)
FireToast
.showToast(context,
"MediaPlayer error (Out of buffer). Please restart your application.");
releaseSound();
mp.release();
mp = null;
return false;
}
});
if (resId == 0) {
FireToast.showToast(context, "File not found");
return false;
}
// mediaPlayer = MediaPlayer.create(context, resId);
try {
if (mediaPlayer != null)
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseSound();
FireToast.showToast(context,"MediaPlayer song completed.");
}
});
mediaPlayer.start();
setPause(false);
return true;
} catch (IllegalStateException e) {
e.printStackTrace();
return false;
}
}
return false;
}
public static boolean releaseSound() {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
mediaPlayer = null;
isPause = false;
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}