Android MediaPlayer: onErrorListener and onCompletionListener work ab-ok

I have this piece of code in an Android Service class that uses MediaPlayer. When I start the player and switch the phone to flight mode after some time of playback (to emulate network errors), the onCompletion listener works after some time. But onError does not cause an I / O error.

Also, when switching the network from Wi-Fi to 3G and vice versa, the stream stops, but there is no error and onCompletion does not work either! Although playback is stopped. Why is this happening? What is wrong with the code? Could this depend on the phone? Android 2.3.5, HTC Explorer. Obviously, the playback is stopped, but there is no error, and onCompletion not onCompletion .

 public class PlayerService extends Service implements MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { /// @Override public boolean onError(MediaPlayer mp, int what, int extra) { // TODO Auto-generated method stub this.playlist="ONERROR"; switch (what){ case MediaPlayer.MEDIA_ERROR_UNKNOWN: Log.e(TAG2, "unknown media playback error"); break; case MediaPlayer.MEDIA_ERROR_SERVER_DIED: Log.e(TAG2, "server connection died"); default: Log.e(TAG2, "generic audio playback error"); break; } switch (extra){ case MediaPlayer.MEDIA_ERROR_IO: Log.e(TAG2, "IO media error"); break; case MediaPlayer.MEDIA_ERROR_MALFORMED: Log.e(TAG2, "media error, malformed"); break; case MediaPlayer.MEDIA_ERROR_UNSUPPORTED: Log.e(TAG2, "unsupported media content"); break; case MediaPlayer.MEDIA_ERROR_TIMED_OUT: Log.e(TAG2, "media timeout error"); break; default: Log.e(TAG2, "unknown playback error"); break; } return true; } @Override public void onCompletion(MediaPlayer arg0) { // TODO Auto-generated method stub this.playlist="COMPLETED"; } /// this.mplayer = MediaPlayer.create(c, Uri.parse(url)); this.mplayer.setOnErrorListener(this); this.mplayer.setOnCompletionListener(this); this.mplayer.start(); 

How can i fix this?

+4
source share
1 answer

First, prepare MediaPlayer:

 mPlayer.prepareAsync(); 

Then launch MediaPlayer:

 mPlayer.start(); 
0
source

Source: https://habr.com/ru/post/1493514/


All Articles