00001 package edu.stanford.hci.r3.actions.types;
00002
00003 import java.io.File;
00004 import java.io.IOException;
00005 import java.net.MalformedURLException;
00006 import java.util.ArrayList;
00007 import java.util.List;
00008
00009 import javax.media.*;
00010
00011 import com.sun.media.codec.audio.mp3.JavaDecoder;
00012
00013 import edu.stanford.hci.r3.actions.R3Action;
00014
00026 public class PlaySoundAction implements R3Action {
00027
00028 private List<PlaySoundListener> notifyOnStop = new ArrayList<PlaySoundListener>();
00029
00030 public static interface PlaySoundListener {
00031 public void soundStopped();
00032 }
00033
00034 public void addStopListener(PlaySoundListener psl) {
00035 notifyOnStop.add(psl);
00036 }
00037
00038 static {
00039
00040 JavaDecoder.main(new String[] {});
00041 System.out.println("Disregard the InvocationTargetException. "
00042 + "It is printed out by the JavaDecoder while registering the mp3 plugin.");
00043 }
00044
00045 private Player player;
00046
00050 private File sound;
00051
00055 public PlaySoundAction(File soundFile) {
00056 sound = soundFile;
00057 }
00058
00062 public void invoke() {
00063
00064 try {
00065 player = Manager.createRealizedPlayer(sound.toURI().toURL());
00066 player.addControllerListener(new ControllerListener() {
00067 public void controllerUpdate(ControllerEvent ce) {
00068 if (ce instanceof StopEvent) {
00069 StopEvent se = (StopEvent) ce;
00070 System.out.println("PlaySoundAction Stopped at: "
00071 + se.getMediaTime().getSeconds() + " seconds");
00072 stop();
00073 for (PlaySoundListener psl : notifyOnStop) {
00074 psl.soundStopped();
00075 }
00076 }
00077 }
00078 });
00079 player.start();
00080 } catch (NoPlayerException e) {
00081 e.printStackTrace();
00082 } catch (CannotRealizeException e) {
00083 e.printStackTrace();
00084 } catch (MalformedURLException e) {
00085 e.printStackTrace();
00086 } catch (IOException e) {
00087 e.printStackTrace();
00088 }
00089 }
00090
00094 public void pause() {
00095 player.stop();
00096 }
00097
00101 public void stop() {
00102 player.stop();
00103 player.close();
00104 }
00105
00106 public void unpause() {
00107 player.start();
00108 }
00109 }