package rpgEngine.Data.Raw.Sound;

import java.io.InputStream;
import javazoom.jl.player.Player;


public class MP3Sound extends GenericSound {
	private String filename;
	private String name;
    private Player player;
	
	public MP3Sound() {
		this("","");
	}
	
	public MP3Sound(String n, String f) {
		name = n;
		filename = f;
		player = null;
	}
	
	
	@Override
	public void play() {
		stop();
		
		if(player == null) {
            openFile();
        }
        
        if(player != null) {
        	try {
        		player.play();
        	}
        	catch(Exception e) {
        		System.err.println("Cannot play music: " + filename);
        	}
        }
	}

	@Override
	public void stop() {
		if(player != null) {
			player.close();
			player = null;
		}
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public String getFilename() {
		return filename;
	}
	
	
	private void openFile() {
    	InputStream stream = null;
    	
        try {        	        	
        	stream = this.getClass().getClassLoader().getResourceAsStream("rpgEngine/Resources/Audio/" + filename);
        	
            player = new Player(stream);
        }
        catch(Exception e) {
            System.err.println("MP3Sound:openFile:" + e.toString());
        }
    }
	
}
