Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A service that prepares MediaPlayer instances and caches the most-requested ones for you
package app
import android.content.Context;
import android.media.MediaPlayer;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
/**
* Pre-loads audio files for quicker playback times
*/
@EBean
public class AudioLoaderService {
public static final int DEFAULT_MAX_PLAYERS_ALLOWED = 2;
private int maxPlayersAllowed;
private Map<String, MediaPlayerWrapper> players;
public AudioLoaderService() {
players = new HashMap<>();
this.maxPlayersAllowed = DEFAULT_MAX_PLAYERS_ALLOWED;
}
public void setMaxPlayersAllowed(int maxPlayersAllowed) {
players = new HashMap<>();
this.maxPlayersAllowed = maxPlayersAllowed;
}
public MediaPlayer getMediaPlayer(String audioFile) throws IOException {
MediaPlayerWrapper wrapper;
if (!players.containsKey(audioFile)) {
ensurePlayerLimitIsRespected();
MediaPlayer player = loadMediaPlayer(audioFile);
wrapper = new MediaPlayerWrapper(audioFile, player);
players.put(audioFile, wrapper);
} else {
wrapper = players.get(audioFile);
}
wrapper.getMediaPlayer().prepare();
wrapper.bumpRequestCount();
return wrapper.getMediaPlayer();
}
private void ensurePlayerLimitIsRespected() {
if (players.size() == maxPlayersAllowed) {
// evict a player
String[] keys = (String[]) players.keySet().toArray(new String[] {});
Arrays.sort(keys, new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return players.get(rhs).getRequestCount() -
players.get(lhs).getRequestCount();
}
});
String keyToRemove = keys[0];
MediaPlayerWrapper wrapper = players.remove(keyToRemove);
wrapper.getMediaPlayer().release();
}
}
private MediaPlayer loadMediaPlayer(String audioFile) throws IOException {
MediaPlayer audioPlayer = new MediaPlayer();
audioPlayer.setDataSource(audioFile);
return audioPlayer;
}
// Release all media players
public void release() {
for (MediaPlayerWrapper wrapper : players.values()) {
wrapper.getMediaPlayer().release();
}
players.clear();
}
private class MediaPlayerWrapper {
private final String audioFile;
private final MediaPlayer player;
private int requestCount;
public MediaPlayerWrapper(String audioFile, MediaPlayer player) {
this.audioFile = audioFile;
this.player = player;
this.requestCount = 0;
}
public void bumpRequestCount() {
requestCount++;
}
public int getRequestCount() {
return requestCount;
}
public MediaPlayer getMediaPlayer() {
return player;
}
@Override
public String toString() {
return String.format("(%s) - (%s)", requestCount, audioFile);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.