我正在尝试使用相同的媒体播放器,但更改数据源。这是我正在尝试做的事情:
private MediaPlayer mMediaPlayer;
public void pickFile1() {
initMediaPlayer("myfile1.mp3");
}
public void pickFile2() {
initMediaPlayer("myfile2.mp3");
}
private void initMediaPlayer(String mediafile) {
// Setup media player, but don't start until user clicks button!
try {
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
} else {
mMediaPlayer.reset(); // so can change data source etc.
}
mMediaPlayer.setOnErrorListener(this);
AssetFileDescriptor afd = getAssets().openFd(mediafile);
mMediaPlayer.setDataSource(afd.getFileDescriptor());
}
catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException: " + e.getMessage());
}
catch (IOException e) {
Log.d(TAG, "IOException: " + e.getMessage());
}
catch (IllegalArgumentException e) {
Log.d(TAG, "IllegalArgumentException: " + e.getMessage());
}
catch (SecurityException e) {
Log.d(TAG, "SecurityException: " + e.getMessage());
}
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); // Keep playing when screen goes off!
}
当我想更改为新的媒体文件时,我只是调用它。不过,它似乎没有成功更改数据源。第一个问题:是否可以这样做,或者我必须释放媒体播放器并为每个新文件创建一个新文件?如果可能,那为什么我的代码不能正常工作?
编辑:好吧,发布和重新创建媒体播放器也不行!它只是一直播放同一首歌!?!?这怎么可能呢?新想法——为每首曲目创建不同的媒体播放器,这真的是我必须要做的吗?这可能是Android中的错误吗?