Android MediaPlayer:onErrorListener和onCompletionListener正常工作

时间:2013-07-25 19:13:05

标签: android stream listener android-mediaplayer

我在Android Service类中有这个代码部分,它使用MediaPlayer。当我启动播放器并在播放一段时间后将手机转为飞行模式(用于模拟网络错误)时,onCompletion监听器会在一段时间内触发。但onError不会触发任何IO错误。

此外,当将网络从Wi-Fi更改为3G并返回时,流停止,但没有错误,onCompletion也不起作用!尽管播放停止了。为什么会这样?代码有什么问题?这取决于手机吗? Android 2.3.5,HTC Explorer。显然播放已停止,但没有错误,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();

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

首先,准备MediaPlayer:

mPlayer.prepareAsync();

然后启动MediaPlayer:

mPlayer.start();