1 package tim.prune.function;
4 import java.io.IOException;
5 import javax.sound.sampled.AudioInputStream;
6 import javax.sound.sampled.AudioSystem;
7 import javax.sound.sampled.Clip;
10 import tim.prune.GenericFunction;
13 * Class to play the current audio file
15 public class PlayAudioFunction extends GenericFunction implements Runnable
17 /** Audio clip used for playing within java */
18 private Clip _clip = null;
23 * @param inApp app object
25 public PlayAudioFunction(App inApp) {
32 public String getNameKey() {
33 return "function.playaudio";
41 // Launch new thread if clip isn't currently playing
43 new Thread(this).start();
48 * Play the audio in a new thread
52 File audioFile = _app.getTrackInfo().getCurrentAudio().getFile();
53 boolean played = false;
54 if (audioFile.exists() && audioFile.isFile() && audioFile.canRead())
56 // First choice is to play using java
57 played = playClip(audioFile);
58 // Second choice is to try the Desktop library from java 6, if available
61 Class<?> d = Class.forName("java.awt.Desktop");
62 d.getDeclaredMethod("open", new Class[] {File.class}).invoke(
63 d.getDeclaredMethod("getDesktop").invoke(null), new Object[] {audioFile});
64 //above code mimics: Desktop.getDesktop().open(audioFile);
67 catch (Exception ignore) {
71 // If the Desktop call failed, need to try backup methods
74 // If system looks like a Mac, try open command
75 String osName = System.getProperty("os.name").toLowerCase();
76 boolean isMacOsx = osName.indexOf("mac os") >= 0 || osName.indexOf("darwin") >= 0;
78 String[] command = new String[] {"open", audioFile.getAbsolutePath()};
80 Runtime.getRuntime().exec(command);
83 catch (IOException ioe) {}
89 // If still not worked, show error message
90 _app.showErrorMessage(getNameKey(), "error.playaudiofailed");
95 * Try to play the sound file using built-in java libraries
96 * @return true if play was successful
98 private boolean playClip(File inFile)
100 boolean success = false;
101 AudioInputStream audioInputStream = null;
105 audioInputStream = AudioSystem.getAudioInputStream(inFile);
106 _clip = AudioSystem.getClip();
107 _clip.open(audioInputStream);
112 } catch (Exception e) {
114 // close the stream to clean up
117 audioInputStream.close();
118 } catch (Exception e) {}
125 * Try to stop a currently playing clip
127 public void stopClip()
129 if (_clip != null && _clip.isActive()) {
134 catch (Exception e) {}
139 * @return percentage of clip currently played, or -1 if not playing
141 public int getPercentage()
144 if (_clip != null && _clip.isActive())
146 long clipLen = _clip.getMicrosecondLength();
148 percent = (int) (_clip.getMicrosecondPosition() * 100.0 / clipLen);