I've been having a problem playing an mp3 file stored in a raw resource: when the file first starts playing, it generates perhaps a quarter of a second of sound and then restarts. (I know that this is basically a duplicate of the problem described here, but the solution offered there hasn't worked for me.) I have tried several things and have made some progress on the problem, but it isn't totally fixed.
Here's how I'm setting up to play a file:
mPlayer.reset();
try {
AssetFileDescriptor afd = getResources().openRawResourceFd(mAudioId);
if (afd == null) {
Toast.makeText(mOwner, "Could not load sound.",
Toast.LENGTH_LONG).show();
return;
}
mPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mPlayer.prepare();
} catch (Exception e) {
Log.d(LOG_TAG, "Could not load sound.", e);
Toast.makeText(mOwner, "Could not load sound.", Toast.LENGTH_LONG)
.show();
}
If I exit the activity (which calls mPlayer.release()
) and come back to it (creating a new MediaPlayer), the stutter is usually (but not always) gone—provided I load the same sound file. I tried a couple of things that made no difference:
- Load the sound file as an asset instead of as a resource.
- Create the MediaPlayer using
MediaPlayer.create(getContext(), mAudioId)
and skip the calls tosetDataSource(...)
andprepare()
.
Then I noticed that LogCat always shows this line at about the time that playback starts:
DEBUG/AudioSink(37): bufferCount (4) is too small and increased to 12
It got me wondering if the stuttering is due to the apparent rebuffering. This led me to try something else:
- After calling
prepare()
, callmPlayer.start()
and immediately callmPlayer.pause()
.
To my pleasant surprise, this had a big effect. A great deal of the stutter is gone, plus no sound (that I can hear) is actually played at that point in the process.
However, it still stutters from time to time when I call mPlayer.start()
for real. Plus, this seems like a huge kludge. Is there any way to kill this problem completely and cleanly?
EDIT More info; not sure if related. If I call pause()
during playback, seek to an earlier position, and call start()
again, I hear a short bit (~1/4 sec) of additional sound from where it was paused before it starts playing at the new position. This seems to point to more buffering problems.
Also, the stuttering (and paused buffer) problems show up on emulators from 1.6 through 3.0.