source: trunk/src/org/apollo/audio/SampledAudioManager.java@ 1007

Last change on this file since 1007 was 1007, checked in by davidb, 8 years ago

Generalization of audio support to allow playback/mixer to be stereo, plus some edits to comments

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