I'm using a SoundPool to play audio clips in my app. All is fine but I need to know when the clip playback has finished.
At the moment I track it in my app by obtaining the duration of each clip using a MediaPlayer instance. That works fine but it looks wasteful to load each file twice, just to get the duration. I could roughly calculate the duration myself knowing the length of the file (available from the AssetFileDescriptor) but I'd still need to know the sample rate and the number of channels.
I see two potential solutions to that problem:
Any suggestions?
Thanks, Max
The code I'm using at the moment (works fine but is rather heavy for the purpose):
String[] fileNames = ...
MediaPlayer mp = new MediaPlayer();
for (String fileName : fileNames) {
AssetFileDescriptor d = context.getAssets().openFd(fileName);
mp.reset();
mp.setDataSource(d.getFileDescriptor(), d.getStartOffset(), d.getLength());
mp.prepare();
int duration = mp.getDuration();
// ...
}
On a side note, this question has already been asked but got no answers.
Did you try this:
String mediaPath = Uri.parse("android.resource://<your-package-name>/raw/filename").getPath();
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(mediaPath);
String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
mmr.release();
But i am not exactly sure that this is lighter than exisiting code.