MediaPlayer didnt update file Duration
I 开发者_如何学Pythonopen a connection to download a stream to a file on the sdcard after writing some bytes I start the MediaPlayer to play the File my problem is that MediaPlayer read just the Duratio calculated in phase of preparation
This is the correct behavior. When you use the MediaPlayer for playing local files, the file is scanned once when the MediaPlayer is initialized and no further scanning will be started. The MediaPlayer does not know that you'll append more data to the file. One solution will be to use the MediaPlayer to stream the file directly over the network.
I have solved this problem by temporarily opening the same file in a new media player, get the duration and release it again. In order to save system resources this should only be done periodically, say every 5th second, and only if the file has actually changed.
public boolean fileSizeHasChanged() {
long currentFileSize = new File(mCurrentMediaFile).length();
if (currentFileSize == mLastFileSize)
return false;
mLastFileSize = currentFileSize;
return true;
}
public int getDuration() {
long currentDurationCheck = System.currentTimeMillis();
if (currentDurationCheck - mLastDurationCheck < 5000)
return mDuration;
mLastDurationCheck = currentDurationCheck;
if (!fileSizeHasChanged())
return mDuration;
// mp is the main media player actual playing, mp2 is the auxillary one
MediaPlayer mp2 = new MediaPlayer();
try {
mp2.setDataSource(mCurrentMediaFile);
mp2.prepare();
mDuration = mp2.getDuration();
mp2.release();
} catch (Exception e) {
e.printStackTrace();
}
return mDuration;
}
精彩评论