package de.heatup.audio;

import java.io.File;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;

public class AudioPlayer {
	
	private ClassLoader cl;
	
	public AudioPlayer() {
		this.cl = Thread.currentThread().getContextClassLoader();
	}
	
	/** plays a file once */
	public void play(String file) {		
		
		try {
			final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));
			clip.addLineListener(new LineListener() {
				
				@Override
				public void update(LineEvent event) {
					if(event.getType() == LineEvent.Type.STOP)
						clip.close();					
				}
			});
			
			/**
			File f = new File(file);
			if(!f.exists()) {
				System.out.println("File not found: " + f.getAbsolutePath());
				return;
			}			
			*/
			
			
			
			clip.open(AudioSystem.getAudioInputStream(cl.getResourceAsStream(file)));
			clip.start();
			
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}	
	}
	
	/** loops every given file */
	public void loop(String file) {
		
		try {
			final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));
			clip.addLineListener(new LineListener() {
				
				@Override
				public void update(LineEvent event) {
					if(event.getType() == LineEvent.Type.STOP)
						clip.close();
				}
			});
			
			/**
			File f = new File(file);
			if(!f.exists()) {
				System.out.println("File not found: " + f.getAbsolutePath());
				return;
			}			
			*/
			
			clip.open(AudioSystem.getAudioInputStream(cl.getResourceAsStream(file)));
			clip.loop(clip.LOOP_CONTINUOUSLY);
			
		} catch(Exception e) {
			e.printStackTrace(System.out);
		}		
	}

}
