package com.hatherly.babykeyboardfun;

import java.net.URL;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.Player;
import javax.media.Time;

/**
 * This is an implementation of the BabySoundPlayer interface, and does
 * the actual playing of the audio clips. This implementation uses the
 * Java Media Framework, but unfortunately cannot play audio clips
 * from within a JAR file. The SoundPlayer_AppletAudio implementation
 * is used in place of this for the game running on the web site, but
 * this implementation is included for reference in case anyone wants
 * to try using JMF.
 */
public class SoundPlayer_JMF implements ControllerListener, BabySoundPlayer {
    
    private Player player;
    private String myFileName = "";
    
    /**
     * Creates a new instance of SoundPlayer
     * @param soundNumber index for the sound clip
     * to load (defined in the Constants class)
     */
    public SoundPlayer_JMF(int soundNumber) {
        try {
            
            String path = SoundPlayer_JMF.class.getResource("/resources/a.jpg").getPath();
            path = path.substring(0,(path.lastIndexOf('/')+1));
            
            if (!path.startsWith("file")) {
                path = "file://" + path;
            }
            
            this.myFileName = Constants.audioFilenames[soundNumber];
            URL url = new URL(path + this.myFileName);

            System.out.println("Loading sound from path: " + url.toString());
            
            
            player = Manager.createPlayer(url);
            
            player.prefetch();
            player.addControllerListener(this);
            
            
        } catch (Exception ex) {
            System.out.println("Error with sound file: " + this.myFileName);
            ex.printStackTrace();
        }
    }
    
    /**
     * Trigger the audio playback
     */
    public void makeSound() {
        try {
            System.out.println("Playing clip");
            player.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * Required callback for JMF to "rewind" the audio at the
     * end of playback
     */
    public synchronized void controllerUpdate(ControllerEvent event) {
        if (player == null)
	    return;
        if (event instanceof EndOfMediaEvent) {
	    // We've reached the end of the media; rewind
	    player.setMediaTime(new Time(0));
	}
    }
    
}


syntax highlighted by Code2HTML, v. 0.9.1