在我的应用程序中,我有一个音频播放器Activity
,它只显示当前歌曲标题和专辑封面以及MediaController
。我还有Service
实现MediaController.MediaPlayerControl
并使用MediaPlayer
进行播放。
一般来说一切正常 - Activity
绑定到Service
并设置MediaController
来控制MediaPlayer
。
当屏幕上显示MediaController
时,开始播放新歌时会出现问题,但仅。如果它被隐藏,或者即使我使用BACK退出Activity
并返回主屏幕,“播放列表”也是如此。处理没有问题。但是,如果MediaContoller
可见,则播放器会静默死亡,搜索/进度条显示开始和结束时间为466:36:07并且logcat显示...
attempt to call getDuration without a valid mediaplayer
我没有在logcat中获得未处理的异常堆栈跟踪 - 只是该消息而MediaPlayer
只是停止播放。我已经用Google搜索了这个错误并获得了近3000次点击(其中大部分都是关于SO的问题)但是我找不到与我匹配的情况。
相关的Activity
代码......
public class AudioPlayerActivity extends Activity
implements OnKeyListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
// Find views here
controller = new MyMediaController(this);
controller.setAnchorView(ll);
controller.setOnKeyListener(this);
}
@Override
protected void onResume() {
super.onResume();
mBound = bindService(new Intent(this, MusicPlayerService.class), mConnection, Context.BIND_AUTO_CREATE);
try {
getCurrentItem();
mediaFilename = currentItem.getTrackName();
coverArtPath = currentItem.getMediaArtUrl();
updateTrackDetails();
Intent playerServiceIntent = new Intent(this, MusicPlayerService.class);
startService(playerServiceIntent);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void showMediaController() {
// Called by onTouchEvent(...)` when the screen is touched
if (mBound) {
controller.setMediaPlayer(mService);
controller.setEnabled(true);
controller.show(0);
}
}
}
Service
包含以下代码......
public class NDroidTEMusicPlayerService extends Service
implements MediaPlayer.OnPreparedListener,
MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener,
AudioManager.OnAudioFocusChangeListener,
MediaPlayerControl {
private void setupMediaPlayer() {
...
try {
mMediaPlayer.setDataSource(trackUrl);
mMediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onCompletion(MediaPlayer mp) {
stop();
mp.reset();
currentItem = playList.getNextItem(isRepeating);
Intent i = new Intent(MYAPP.ACTION_MYAPP_UPDATE_PLAY_VIEW);
i.putExtra("current_item", currentItem);
sendBroadcast(i);
setupMediaPlayer();
}
@Override
public int getDuration() {
int duration = 0;
if (mMediaPlayer != null)
duration = mMediaPlayer.getDuration();
return duration;
}
}