package greenfoot.sound;

import greenfoot.util.GreenfootUtil;

import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.UnsupportedAudioFileException;


| Class responsible for creating Sounds and loading them. | | @author Poul Henriksen | public class SoundFactory {
| singleton | private static SoundFactory instance;
| Collection of all sounds, which can be used to affect the state of all | sounds, for instance it can pause/resume all sounds. | private SoundCollection soundCollection;
| Only use clips when the size of the clip is below this value (size of the | file in bytes). | TODO: make this user configurable for platforms where | clips don't work so well. What about applets? | private static final int maxClipSize = 500 * 1000; private SoundFactory() { soundCollection = new SoundCollection(); for (String soundFile : GreenfootUtil.getSoundFiles()) { Sound s = createSound(soundFile, true); if (s instanceof SoundClip) ((SoundClip)s).preLoad(); } } public synchronized static SoundFactory getInstance() { if (instance == null) { instance = new SoundFactory(); } return instance; } public SoundCollection getSoundCollection() { return soundCollection; }
| Creates the sound from file. | | @param file Name of a file or an url | @param quiet if true, failure is silent; otherwise an IllegalArgumentException may be thrown | @throws IllegalArgumentException if the specified sound is invalid or cannot be played, unless quiet is true | @return a sound, or if quiet is true, possibly null | public Sound createSound(final String file, boolean quiet) { try { URL url = GreenfootUtil.getURL(file, "sounds"); int size = url.openConnection().getContentLength(); if (isMidi(url)) { return new MidiFileSound(url, soundCollection); } else if (!GreenfootUtil.isMp3LibAvailable() && isMp3(url)) { SoundExceptionHandler.handleMp3LibNotAvailable(); } else if (isMp3(url)) { return new SoundStream(new Mp3AudioInputStream(url), soundCollection); } else if (isJavaAudioStream(size)) { return new SoundStream(new JavaAudioInputStream(url), soundCollection); } else { return new SoundClip(file, url, soundCollection); } } catch (IOException e) { if (! quiet) { SoundExceptionHandler.handleIOException(e, file); } } catch (UnsupportedAudioFileException e) { if (! quiet) { SoundExceptionHandler.handleUnsupportedAudioFileException(e, file); } } return null; } private boolean isJavaAudioStream(int size) { return size == -1 || size > maxClipSize; } private boolean isMidi(URL url) { String lowerCaseName = url.toString().toLowerCase(); return lowerCaseName.endsWith("mid") || lowerCaseName.endsWith("midi"); } private boolean isMp3(URL url) { String lowerCaseName = url.toString().toLowerCase(); return lowerCaseName.endsWith("mp3"); } }
top, use, map, class SoundFactory

.   SoundFactory
.   getInstance
.   getSoundCollection
.   createSound
.   isJavaAudioStream
.   isMidi
.   isMp3




135 neLoCode + 14 LoComm