package greenfoot.sound;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;


| A cache for soundclip data. | | @author Davin McCall | public class ClipCache {
| Data for clips that aren't currently in use | private LinkedHashMap<String,ClipData> freeClips = new LinkedHashMap<String,ClipData>(); private int numberFreeClips = 0; private static int MAX_CACHED_CLIPS = 20;
| Data for clips that are in use | private Map<String,ClipData> cachedClips = new HashMap<String,ClipData>(); public synchronized ClipData getCachedClip(URL url) throws IOException, UnsupportedAudioFileException { String urlStr = url.toString(); ClipData data = cachedClips.get(urlStr); if (data == null) { data = freeClips.remove(urlStr); if (data != null) { numberFreeClips --; cachedClips.put(urlStr, data); } } if (data == null) { AudioInputStream ais = AudioSystem.getAudioInputStream(url); AudioFormat af = ais.getFormat(); long frameLength = ais.getFrameLength(); int total = (int)(af.getFrameSize() * frameLength); byte[] allBytes = new byte[(int)(af.getFrameSize() * frameLength)]; int pos = 0; try { while (pos < total){ int r = ais.read(allBytes, pos, total - pos); if (r == -1) { break; } pos += r; } } finally { ais.close(); } data = new ClipData(urlStr, allBytes, af, (int) frameLength); } else { data.addUser(); } return data; } public synchronized void releaseClipData(ClipData data) { if (data.release()) { cachedClips.remove(data.getUrl()); freeClips.put(data.getUrl(), data); numberFreeClips++; if (numberFreeClips > MAX_CACHED_CLIPS) { Iterator<ClipData> it = freeClips.values().iterator(); it.next(); it.remove(); numberFreeClips = MAX_CACHED_CLIPS; } } } }
top, use, map, class ClipCache

.   getCachedClip
.   releaseClipData




113 neLoCode + 4 LoComm