source: trunk/src_apollo/org/apollo/audio/SampledAudioManager.java@ 315

Last change on this file since 315 was 315, checked in by bjn8, 16 years ago

Apollo spin-off added

File size: 11.0 KB
Line 
1package org.apollo.audio;
2
3import java.util.ArrayList;
4import java.util.LinkedList;
5import java.util.List;
6
7import javax.sound.sampled.AudioFormat;
8import javax.sound.sampled.AudioSystem;
9import javax.sound.sampled.DataLine;
10import javax.sound.sampled.Mixer;
11import javax.sound.sampled.Line.Info;
12
13import org.apollo.mvc.AbstractSubject;
14import org.apollo.mvc.SubjectChangedEvent;
15import org.apollo.util.AudioSystemLog;
16
17/**
18 * Manages all audio services. Initializes and shutsdown the audio system when
19 * Expeditee opens/closes.
20 *
21 * Handles audio formats.
22 *
23 * @author Brook Novak
24 *
25 */
26public final class SampledAudioManager extends AbstractSubject {
27
28 /** All internal formats have the same sample rate. */
29 public static final float PLAYBACK_SAMPLE_RATE = 44100.0f; // Audacitys default
30
31 //public static final float PLAYBACK_SAMPLE_RATE = 22050.0f; // Meldexes internal rate .. todo: fix conversions to use better rate
32
33 // Used for describing the ideal default format for recorded audio and converting un-supported
34 // imported audio to... The actual formats may differ depending on the data lines used
35
36 // note: Must be PCM, Mono, 16 bit.
37 private static final AudioFormat DESIRED_FORMAT = new AudioFormat( // Linear PCM Encoding
38 PLAYBACK_SAMPLE_RATE, // Always conform to PLAYBACK_SAMPLE_RATE
39 16, // bits per sample. Must be 16. Audacitys default
40 1, // Always use mono. Audacitys default
41 false, // ALWAYS USED SIGNED FOR BEST PERFORMACE - JAVA DOES NOT HAVE UNSIGNED TYPES
42 true // Byte order
43 );
44
45 private List<Mixer.Info> inputMixers = new LinkedList<Mixer.Info>();
46
47 private Mixer inputMixer = null; // capture
48 private Mixer outputMixer = null; // playback
49
50 // Loaded with all supported playback formats on construction
51 private AudioFormat[] supportedPlaybackFormats = null;
52 private AudioFormat defaultPlaybackFormat = null;
53 private AudioFormat defaultCaptureFormat = null;
54
55 private static SampledAudioManager instance = new SampledAudioManager(); // single design pattern
56
57 /**
58 * @return The singleton instance of the SampledAudioManager
59 */
60 public static SampledAudioManager getInstance() { // single design pattern
61 return instance;
62 }
63
64 private SampledAudioManager() { // singleton design pattern
65 LoadMixers();
66 }
67
68 /**
69 * Detects all input mixers currently installed on system. Selects the first input mixer it finds.
70 * The output mixer is set to java software sound engine.
71 */
72 private void LoadMixers() {
73
74 // Set output mixer as java software mixer
75 outputMixer = AudioSystem.getMixer(null);
76
77 if (outputMixer == null) {
78 AudioSystemLog.printError("Could not find output audio device");
79
80 } else { // Create default output audio format based on output mixer
81
82 AudioSystemLog.println("Using " + outputMixer + " as output mixer");
83
84 // Discover all supported playback formats.
85 loadSupportedPlaybackFormats();
86
87 // Select the default playback format.
88 defaultPlaybackFormat = getBestMatchedSupportedFormat(supportedPlaybackFormats, DESIRED_FORMAT);
89
90 // Safety
91 if (defaultPlaybackFormat == null) {
92 defaultPlaybackFormat = DESIRED_FORMAT;
93 AudioSystemLog.printError("Unable to find a suitable default format for audio playback");
94 }
95
96 AudioSystemLog.println("Default playback format: " + defaultPlaybackFormat);
97
98 }
99
100 // Get all installed mixers on the system
101 Mixer.Info[] mixers = AudioSystem.getMixerInfo();
102
103 Mixer.Info inputMixerInfo = null;
104
105 // Determine which mixers can record / playback.
106 for (Mixer.Info mi : mixers) {
107
108 Mixer mixer = AudioSystem.getMixer(mi);
109 if (mixer.getTargetLineInfo().length > 0) {
110 inputMixers.add(mi);
111 if (inputMixerInfo == null) { // select a default mixer
112 inputMixerInfo = mi;
113 }
114 }
115 }
116
117 // Set the current input mixer
118 inputMixer = null;
119 if (inputMixerInfo != null) {
120 setCurrentInputMixure(inputMixerInfo); // this will load the new capture audio format
121 } else {
122 AudioSystemLog.printError("Could not find input audio device");
123 }
124
125 }
126
127 /**
128 * Discovers all supported playback audio formats.
129 */
130 private void loadSupportedPlaybackFormats() {
131
132 LinkedList<AudioFormat> supported = new LinkedList<AudioFormat>();
133
134 for (Info inf : outputMixer.getSourceLineInfo()) {
135
136 if (inf instanceof DataLine.Info) {
137 DataLine.Info dinf = (DataLine.Info)inf;
138
139 for (AudioFormat format : dinf.getFormats()) {
140 supported.add(format);
141 }
142 }
143 }
144
145 supportedPlaybackFormats = supported.toArray(new AudioFormat[0]);
146
147 }
148
149 /**
150 * Loads the best fitting capture format supported by the input mixer. Only format that
151 * are supported for playback are considered.
152 *
153 * Sets defaultCaptureFormat... Will be null if current input mixer does not support
154 * the right formats. Or if no input mixer is set.
155 */
156 private void loadSupportedCaptureFormat() {
157
158 defaultCaptureFormat = null;
159
160 //AudioSystemLog.println("Detecting supported capture formats:");
161
162 if (inputMixer == null) return;
163
164 LinkedList<AudioFormat> supported = new LinkedList<AudioFormat>();
165
166 for (Info inf : inputMixer.getTargetLineInfo()) {
167
168 if (inf instanceof DataLine.Info) {
169 DataLine.Info dinf = (DataLine.Info)inf;
170
171 for (AudioFormat format : dinf.getFormats()) {
172 if (isFormatSupportedForPlayback(format)) { // only consider if can playback
173 supported.add(format);
174 //AudioSystemLog.println(format);
175 }
176
177 }
178 }
179 }
180
181 //AudioSystemLog.println("*End of format list");
182
183 // Select the best fitting format supported by the input mixer
184 defaultCaptureFormat = getBestMatchedSupportedFormat(
185 supported.toArray(new AudioFormat[0]),
186 DESIRED_FORMAT);
187
188 AudioSystemLog.println("Using audio format for capturing: " + defaultCaptureFormat);
189 }
190
191 /**
192 * @return The default playback format for this system.
193 * Never null, even if output mixer unavailable.
194 */
195 public AudioFormat getDefaultPlaybackFormat() {
196 return defaultPlaybackFormat;
197 }
198
199 /**
200 * @return The default capture format for this system. Null if no input mixer set/available
201 */
202 AudioFormat getDefaultCaptureFormat() {
203 return defaultCaptureFormat;
204 }
205
206 /**
207 * Finds the best matching format.
208 *
209 * All formats that are not PCM encoded and does not use mono channels are excluded.
210 *
211 * @param targets
212 *
213 * @param toMatch
214 *
215 * @return
216 * The best matched and supported Audio format.
217 * Null there were no supported formats.
218 */
219 private AudioFormat getBestMatchedSupportedFormat(AudioFormat[] targets, AudioFormat toMatch) {
220 assert(targets != null);
221
222 assert(toMatch != null);
223
224 int bestIndex = -1;
225 float bestScore = -1.0f;
226
227 for (int i = 0; i < targets.length; i++) {
228
229 AudioFormat candiate = targets[i];
230
231 // Not cadidate if not in appollos format.
232 if (!candiate.getEncoding().toString().startsWith("PCM")
233 || candiate.getChannels() != 1
234 || candiate.getSampleSizeInBits() != 16
235 || (candiate.getSampleRate() != AudioSystem.NOT_SPECIFIED &&
236 candiate.getSampleRate() != PLAYBACK_SAMPLE_RATE))
237 continue;
238
239 float score = 0.0f;
240
241 // Compute match score
242 if (candiate.isBigEndian() == toMatch.isBigEndian()) {
243 score += 0.5f;
244 }
245
246 if (candiate.getSampleSizeInBits() == toMatch.getSampleSizeInBits()) {
247 score += 2.0f;
248 }
249
250 if (candiate.getSampleRate() == toMatch.getSampleRate()
251 || candiate.getSampleRate() == AudioSystem.NOT_SPECIFIED) {
252 score += 2.0f;
253 }
254
255 if (candiate.getEncoding() == toMatch.getEncoding()) { // there are different PCM encodings
256 score += 6.0f;
257 }
258
259 if (bestIndex == -1 || score > bestScore) {
260 bestIndex = i;
261 bestScore = score;
262 }
263 }
264
265 if (bestIndex == -1) return null;
266
267 // Be sure to specificy the sample rate if not specified
268 AudioFormat bestMatch = targets[bestIndex];
269 if (bestMatch.getSampleRate() == AudioSystem.NOT_SPECIFIED) {
270 bestMatch = new AudioFormat(
271 bestMatch.getEncoding(),
272 toMatch.getSampleRate(),
273 bestMatch.getSampleSizeInBits(),
274 bestMatch.getChannels(),
275 bestMatch.getFrameSize(),
276 toMatch.getFrameRate(),
277 bestMatch.isBigEndian()
278 );
279 }
280
281 return bestMatch;
282 }
283
284
285 /**
286 * Determines if an audio format requires conversion in order to be used
287 * in Apollos.
288 *
289 * Audio formats must be in PCM, mono, 16-bit sample-size,
290 * SampledAudioManager#PLAYBACK_SAMPLE_RATE sample-rate and be supported
291 * by the output mixer.
292 *
293 * @param format
294 * The format to test. Must not be null.
295 *
296 * @return
297 * True if the given format requires formatting.
298 *
299 * @throws NullPointerException
300 * If format is null.
301 */
302 public synchronized boolean isFormatSupportedForPlayback(AudioFormat format) {
303
304 if (format == null) throw new NullPointerException("format");
305
306 if(!format.getEncoding().toString().startsWith("PCM") || format.getChannels() != 1
307 || format.getSampleSizeInBits() != 16
308 || (format.getSampleRate() != AudioSystem.NOT_SPECIFIED &&
309 format.getSampleRate() != PLAYBACK_SAMPLE_RATE)) {
310 return false;
311 }
312
313 // Check that the format is supported by the output mixer
314 for (AudioFormat supported : supportedPlaybackFormats) {
315 if (supported.getChannels() != 1) continue;
316 if (
317 format.getEncoding() == supported.getEncoding()
318
319 && format.getSampleSizeInBits() == supported.getSampleSizeInBits()
320
321 && format.isBigEndian() == supported.isBigEndian()
322
323 && (supported.getSampleRate() == AudioSystem.NOT_SPECIFIED
324 || format.getSampleRate() == supported.getSampleRate())
325
326 ) {
327 return true;
328 }
329 }
330
331 return false;
332 }
333
334
335
336 /**
337 * Sets the current input mixure. Returns immediatly if equal to current input mixer.
338 * Fires a AudioSubjectChangedEvent.INPUT_MIXER event.
339 *
340 * @param mi The Mixer.Info of the Mixer to set as the new mixer for input.
341 *
342 * @throws IllegalArgumentException
343 * if the info object does not represent a mixer installed on the system
344 *
345 * @throws NullPointerException
346 * if mi is null.
347 */
348 public void setCurrentInputMixure(Mixer.Info mi) {
349 if (mi == null)
350 throw new NullPointerException("mi");
351 else if (!inputMixers.contains(mi))
352 throw new IllegalArgumentException("Mixer not supported");
353
354 Mixer newMixer = AudioSystem.getMixer(mi); // also throws IllegalArgumentException
355
356 if (newMixer.equals(inputMixer)) return;
357
358 inputMixer = newMixer;
359
360 // Determine new capture format according to new input mixer
361 loadSupportedCaptureFormat();
362
363 fireSubjectChanged(new SubjectChangedEvent(ApolloSubjectChangedEvent.INPUT_MIXER));
364
365 }
366
367 /**
368 * @return The current input mixer. Null if none is supported.
369 */
370 Mixer getCurrentInputMixure() {
371 return inputMixer;
372 }
373
374 /**
375 * @return The current output mixer. Null if none is supported.
376 */
377 Mixer getOutputMixure() {
378 return outputMixer;
379 }
380
381 /**
382 * @return The current input mixer. Null if none is supported.
383 */
384 public Mixer.Info getCurrentInputMixureInfo() {
385 return inputMixer.getMixerInfo();
386 }
387
388 /**
389 * @return A copy of the list of all supported input mixers. Can be empty if none is supported.
390 */
391 public List<Mixer.Info> getSupportedInputMixures() {
392 return new ArrayList<Mixer.Info>(this.inputMixers);
393 }
394
395}
Note: See TracBrowser for help on using the repository browser.