1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.awt.GraphicsEnvironment;
|
---|
7 | import java.io.IOException;
|
---|
8 | import java.net.URL;
|
---|
9 |
|
---|
10 | import javax.sound.sampled.AudioFormat;
|
---|
11 | import javax.sound.sampled.AudioInputStream;
|
---|
12 | import javax.sound.sampled.AudioSystem;
|
---|
13 | import javax.sound.sampled.DataLine;
|
---|
14 | import javax.sound.sampled.LineUnavailableException;
|
---|
15 | import javax.sound.sampled.SourceDataLine;
|
---|
16 | import javax.sound.sampled.UnsupportedAudioFileException;
|
---|
17 | import javax.swing.JOptionPane;
|
---|
18 |
|
---|
19 | import org.openstreetmap.josm.Main;
|
---|
20 |
|
---|
21 | /**
|
---|
22 | * Creates and controls a separate audio player thread.
|
---|
23 | *
|
---|
24 | * @author David Earl <david@frankieandshadow.com>
|
---|
25 | * @since 547
|
---|
26 | */
|
---|
27 | public final class AudioPlayer extends Thread {
|
---|
28 |
|
---|
29 | private static volatile AudioPlayer audioPlayer;
|
---|
30 |
|
---|
31 | private enum State { INITIALIZING, NOTPLAYING, PLAYING, PAUSED, INTERRUPTED }
|
---|
32 |
|
---|
33 | private enum Command { PLAY, PAUSE }
|
---|
34 |
|
---|
35 | private enum Result { WAITING, OK, FAILED }
|
---|
36 |
|
---|
37 | private State state;
|
---|
38 | private URL playingUrl;
|
---|
39 | private final double leadIn; // seconds
|
---|
40 | private final double calibration; // ratio of purported duration of samples to true duration
|
---|
41 | private double position; // seconds
|
---|
42 | private double bytesPerSecond;
|
---|
43 | private static long chunk = 4000; /* bytes */
|
---|
44 | private double speed = 1.0;
|
---|
45 |
|
---|
46 | /**
|
---|
47 | * Passes information from the control thread to the playing thread
|
---|
48 | */
|
---|
49 | private class Execute {
|
---|
50 | private Command command;
|
---|
51 | private Result result;
|
---|
52 | private Exception exception;
|
---|
53 | private URL url;
|
---|
54 | private double offset; // seconds
|
---|
55 | private double speed; // ratio
|
---|
56 |
|
---|
57 | /*
|
---|
58 | * Called to execute the commands in the other thread
|
---|
59 | */
|
---|
60 | protected void play(URL url, double offset, double speed) throws Exception {
|
---|
61 | this.url = url;
|
---|
62 | this.offset = offset;
|
---|
63 | this.speed = speed;
|
---|
64 | command = Command.PLAY;
|
---|
65 | result = Result.WAITING;
|
---|
66 | send();
|
---|
67 | }
|
---|
68 |
|
---|
69 | protected void pause() throws Exception {
|
---|
70 | command = Command.PAUSE;
|
---|
71 | send();
|
---|
72 | }
|
---|
73 |
|
---|
74 | private void send() throws Exception {
|
---|
75 | result = Result.WAITING;
|
---|
76 | interrupt();
|
---|
77 | while (result == Result.WAITING) {
|
---|
78 | sleep(10);
|
---|
79 | }
|
---|
80 | if (result == Result.FAILED)
|
---|
81 | throw exception;
|
---|
82 | }
|
---|
83 |
|
---|
84 | private void possiblyInterrupt() throws InterruptedException {
|
---|
85 | if (interrupted() || result == Result.WAITING)
|
---|
86 | throw new InterruptedException();
|
---|
87 | }
|
---|
88 |
|
---|
89 | protected void failed(Exception e) {
|
---|
90 | exception = e;
|
---|
91 | result = Result.FAILED;
|
---|
92 | state = State.NOTPLAYING;
|
---|
93 | }
|
---|
94 |
|
---|
95 | protected void ok(State newState) {
|
---|
96 | result = Result.OK;
|
---|
97 | state = newState;
|
---|
98 | }
|
---|
99 |
|
---|
100 | protected double offset() {
|
---|
101 | return offset;
|
---|
102 | }
|
---|
103 |
|
---|
104 | protected double speed() {
|
---|
105 | return speed;
|
---|
106 | }
|
---|
107 |
|
---|
108 | protected URL url() {
|
---|
109 | return url;
|
---|
110 | }
|
---|
111 |
|
---|
112 | protected Command command() {
|
---|
113 | return command;
|
---|
114 | }
|
---|
115 | }
|
---|
116 |
|
---|
117 | private final Execute command;
|
---|
118 |
|
---|
119 | /**
|
---|
120 | * Plays a WAV audio file from the beginning. See also the variant which doesn't
|
---|
121 | * start at the beginning of the stream
|
---|
122 | * @param url The resource to play, which must be a WAV file or stream
|
---|
123 | * @throws Exception audio fault exception, e.g. can't open stream, unhandleable audio format
|
---|
124 | */
|
---|
125 | public static void play(URL url) throws Exception {
|
---|
126 | AudioPlayer.getInstance().command.play(url, 0.0, 1.0);
|
---|
127 | }
|
---|
128 |
|
---|
129 | /**
|
---|
130 | * Plays a WAV audio file from a specified position.
|
---|
131 | * @param url The resource to play, which must be a WAV file or stream
|
---|
132 | * @param seconds The number of seconds into the audio to start playing
|
---|
133 | * @throws Exception audio fault exception, e.g. can't open stream, unhandleable audio format
|
---|
134 | */
|
---|
135 | public static void play(URL url, double seconds) throws Exception {
|
---|
136 | AudioPlayer.getInstance().command.play(url, seconds, 1.0);
|
---|
137 | }
|
---|
138 |
|
---|
139 | /**
|
---|
140 | * Plays a WAV audio file from a specified position at variable speed.
|
---|
141 | * @param url The resource to play, which must be a WAV file or stream
|
---|
142 | * @param seconds The number of seconds into the audio to start playing
|
---|
143 | * @param speed Rate at which audio playes (1.0 = real time, > 1 is faster)
|
---|
144 | * @throws Exception audio fault exception, e.g. can't open stream, unhandleable audio format
|
---|
145 | */
|
---|
146 | public static void play(URL url, double seconds, double speed) throws Exception {
|
---|
147 | AudioPlayer.getInstance().command.play(url, seconds, speed);
|
---|
148 | }
|
---|
149 |
|
---|
150 | /**
|
---|
151 | * Pauses the currently playing audio stream. Does nothing if nothing playing.
|
---|
152 | * @throws Exception audio fault exception, e.g. can't open stream, unhandleable audio format
|
---|
153 | */
|
---|
154 | public static void pause() throws Exception {
|
---|
155 | AudioPlayer.getInstance().command.pause();
|
---|
156 | }
|
---|
157 |
|
---|
158 | /**
|
---|
159 | * To get the Url of the playing or recently played audio.
|
---|
160 | * @return url - could be null
|
---|
161 | */
|
---|
162 | public static URL url() {
|
---|
163 | return AudioPlayer.getInstance().playingUrl;
|
---|
164 | }
|
---|
165 |
|
---|
166 | /**
|
---|
167 | * Whether or not we are paused.
|
---|
168 | * @return boolean whether or not paused
|
---|
169 | */
|
---|
170 | public static boolean paused() {
|
---|
171 | return AudioPlayer.getInstance().state == State.PAUSED;
|
---|
172 | }
|
---|
173 |
|
---|
174 | /**
|
---|
175 | * Whether or not we are playing.
|
---|
176 | * @return boolean whether or not playing
|
---|
177 | */
|
---|
178 | public static boolean playing() {
|
---|
179 | return AudioPlayer.getInstance().state == State.PLAYING;
|
---|
180 | }
|
---|
181 |
|
---|
182 | /**
|
---|
183 | * How far we are through playing, in seconds.
|
---|
184 | * @return double seconds
|
---|
185 | */
|
---|
186 | public static double position() {
|
---|
187 | return AudioPlayer.getInstance().position;
|
---|
188 | }
|
---|
189 |
|
---|
190 | /**
|
---|
191 | * Speed at which we will play.
|
---|
192 | * @return double, speed multiplier
|
---|
193 | */
|
---|
194 | public static double speed() {
|
---|
195 | return AudioPlayer.getInstance().speed;
|
---|
196 | }
|
---|
197 |
|
---|
198 | /**
|
---|
199 | * Returns the singleton object, and if this is the first time, creates it along with
|
---|
200 | * the thread to support audio
|
---|
201 | * @return the unique instance
|
---|
202 | */
|
---|
203 | private static AudioPlayer getInstance() {
|
---|
204 | if (audioPlayer != null)
|
---|
205 | return audioPlayer;
|
---|
206 | try {
|
---|
207 | audioPlayer = new AudioPlayer();
|
---|
208 | return audioPlayer;
|
---|
209 | } catch (RuntimeException ex) {
|
---|
210 | Main.error(ex);
|
---|
211 | return null;
|
---|
212 | }
|
---|
213 | }
|
---|
214 |
|
---|
215 | /**
|
---|
216 | * Resets the audio player.
|
---|
217 | */
|
---|
218 | public static void reset() {
|
---|
219 | if (audioPlayer != null) {
|
---|
220 | try {
|
---|
221 | pause();
|
---|
222 | } catch (Exception e) {
|
---|
223 | Main.warn(e);
|
---|
224 | }
|
---|
225 | audioPlayer.playingUrl = null;
|
---|
226 | }
|
---|
227 | }
|
---|
228 |
|
---|
229 | private AudioPlayer() {
|
---|
230 | state = State.INITIALIZING;
|
---|
231 | command = new Execute();
|
---|
232 | playingUrl = null;
|
---|
233 | leadIn = Main.pref.getDouble("audio.leadin", 1.0 /* default, seconds */);
|
---|
234 | calibration = Main.pref.getDouble("audio.calibration", 1.0 /* default, ratio */);
|
---|
235 | start();
|
---|
236 | while (state == State.INITIALIZING) {
|
---|
237 | yield();
|
---|
238 | }
|
---|
239 | }
|
---|
240 |
|
---|
241 | /**
|
---|
242 | * Starts the thread to actually play the audio, per Thread interface
|
---|
243 | * Not to be used as public, though Thread interface doesn't allow it to be made private
|
---|
244 | */
|
---|
245 | @Override public void run() {
|
---|
246 | /* code running in separate thread */
|
---|
247 |
|
---|
248 | playingUrl = null;
|
---|
249 | AudioInputStream audioInputStream = null;
|
---|
250 | SourceDataLine audioOutputLine = null;
|
---|
251 | AudioFormat audioFormat;
|
---|
252 | byte[] abData = new byte[(int) chunk];
|
---|
253 |
|
---|
254 | for (;;) {
|
---|
255 | try {
|
---|
256 | switch (state) {
|
---|
257 | case INITIALIZING:
|
---|
258 | // we're ready to take interrupts
|
---|
259 | state = State.NOTPLAYING;
|
---|
260 | break;
|
---|
261 | case NOTPLAYING:
|
---|
262 | case PAUSED:
|
---|
263 | sleep(200);
|
---|
264 | break;
|
---|
265 | case PLAYING:
|
---|
266 | command.possiblyInterrupt();
|
---|
267 | for (;;) {
|
---|
268 | int nBytesRead;
|
---|
269 | nBytesRead = audioInputStream.read(abData, 0, abData.length);
|
---|
270 | position += nBytesRead / bytesPerSecond;
|
---|
271 | command.possiblyInterrupt();
|
---|
272 | if (nBytesRead < 0) {
|
---|
273 | break;
|
---|
274 | }
|
---|
275 | audioOutputLine.write(abData, 0, nBytesRead); // => int nBytesWritten
|
---|
276 | command.possiblyInterrupt();
|
---|
277 | }
|
---|
278 | // end of audio, clean up
|
---|
279 | audioOutputLine.drain();
|
---|
280 | audioOutputLine.close();
|
---|
281 | audioOutputLine = null;
|
---|
282 | Utils.close(audioInputStream);
|
---|
283 | audioInputStream = null;
|
---|
284 | playingUrl = null;
|
---|
285 | state = State.NOTPLAYING;
|
---|
286 | command.possiblyInterrupt();
|
---|
287 | break;
|
---|
288 | default: // Do nothing
|
---|
289 | }
|
---|
290 | } catch (InterruptedException e) {
|
---|
291 | interrupted(); // just in case we get an interrupt
|
---|
292 | State stateChange = state;
|
---|
293 | state = State.INTERRUPTED;
|
---|
294 | try {
|
---|
295 | switch (command.command()) {
|
---|
296 | case PLAY:
|
---|
297 | double offset = command.offset();
|
---|
298 | speed = command.speed();
|
---|
299 | if (playingUrl != command.url() ||
|
---|
300 | stateChange != State.PAUSED ||
|
---|
301 | offset != 0) {
|
---|
302 | if (audioInputStream != null) {
|
---|
303 | Utils.close(audioInputStream);
|
---|
304 | audioInputStream = null;
|
---|
305 | }
|
---|
306 | playingUrl = command.url();
|
---|
307 | audioInputStream = AudioSystem.getAudioInputStream(playingUrl);
|
---|
308 | audioFormat = audioInputStream.getFormat();
|
---|
309 | long nBytesRead = 0;
|
---|
310 | position = 0.0;
|
---|
311 | offset -= leadIn;
|
---|
312 | double calibratedOffset = offset * calibration;
|
---|
313 | bytesPerSecond = audioFormat.getFrameRate() /* frames per second */
|
---|
314 | * audioFormat.getFrameSize() /* bytes per frame */;
|
---|
315 | if (speed * bytesPerSecond > 256000.0) {
|
---|
316 | speed = 256000 / bytesPerSecond;
|
---|
317 | }
|
---|
318 | if (calibratedOffset > 0.0) {
|
---|
319 | long bytesToSkip = (long) (calibratedOffset /* seconds (double) */ * bytesPerSecond);
|
---|
320 | // skip doesn't seem to want to skip big chunks, so reduce it to smaller ones
|
---|
321 | while (bytesToSkip > chunk) {
|
---|
322 | nBytesRead = audioInputStream.skip(chunk);
|
---|
323 | if (nBytesRead <= 0)
|
---|
324 | throw new IOException(tr("This is after the end of the recording"));
|
---|
325 | bytesToSkip -= nBytesRead;
|
---|
326 | }
|
---|
327 | while (bytesToSkip > 0) {
|
---|
328 | long skippedBytes = audioInputStream.skip(bytesToSkip);
|
---|
329 | bytesToSkip -= skippedBytes;
|
---|
330 | if (skippedBytes == 0) {
|
---|
331 | // Avoid inifinite loop
|
---|
332 | Main.warn("Unable to skip bytes from audio input stream");
|
---|
333 | bytesToSkip = 0;
|
---|
334 | }
|
---|
335 | }
|
---|
336 | position = offset;
|
---|
337 | }
|
---|
338 | if (audioOutputLine != null) {
|
---|
339 | audioOutputLine.close();
|
---|
340 | }
|
---|
341 | audioFormat = new AudioFormat(audioFormat.getEncoding(),
|
---|
342 | audioFormat.getSampleRate() * (float) (speed * calibration),
|
---|
343 | audioFormat.getSampleSizeInBits(),
|
---|
344 | audioFormat.getChannels(),
|
---|
345 | audioFormat.getFrameSize(),
|
---|
346 | audioFormat.getFrameRate() * (float) (speed * calibration),
|
---|
347 | audioFormat.isBigEndian());
|
---|
348 | DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
|
---|
349 | audioOutputLine = (SourceDataLine) AudioSystem.getLine(info);
|
---|
350 | audioOutputLine.open(audioFormat);
|
---|
351 | audioOutputLine.start();
|
---|
352 | }
|
---|
353 | stateChange = State.PLAYING;
|
---|
354 | break;
|
---|
355 | case PAUSE:
|
---|
356 | stateChange = State.PAUSED;
|
---|
357 | break;
|
---|
358 | default: // Do nothing
|
---|
359 | }
|
---|
360 | command.ok(stateChange);
|
---|
361 | } catch (LineUnavailableException | IOException | UnsupportedAudioFileException |
|
---|
362 | SecurityException | IllegalArgumentException startPlayingException) {
|
---|
363 | Main.error(startPlayingException);
|
---|
364 | command.failed(startPlayingException); // sets state
|
---|
365 | }
|
---|
366 | } catch (IOException e) {
|
---|
367 | state = State.NOTPLAYING;
|
---|
368 | Main.error(e);
|
---|
369 | }
|
---|
370 | }
|
---|
371 | }
|
---|
372 |
|
---|
373 | /**
|
---|
374 | * Shows a popup audio error message for the given exception.
|
---|
375 | * @param ex The exception used as error reason. Cannot be {@code null}.
|
---|
376 | */
|
---|
377 | public static void audioMalfunction(Exception ex) {
|
---|
378 | String msg = ex.getMessage();
|
---|
379 | if (msg == null)
|
---|
380 | msg = tr("unspecified reason");
|
---|
381 | else
|
---|
382 | msg = tr(msg);
|
---|
383 | Main.error(msg);
|
---|
384 | if (!GraphicsEnvironment.isHeadless()) {
|
---|
385 | JOptionPane.showMessageDialog(Main.parent,
|
---|
386 | "<html><p>" + msg + "</p></html>",
|
---|
387 | tr("Error playing sound"), JOptionPane.ERROR_MESSAGE);
|
---|
388 | }
|
---|
389 | }
|
---|
390 | }
|
---|