/* JEsd
 * Copyright (C) 1999 JCraft Inc.
 *  
 * Written by: 1999 ymnk
 *   
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
   
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 * 
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

package com.jcraft.jesd;

//import javax.media.sound.midi.*;
//import javax.media.sound.sampled.*;
import javax.sound.midi.*;
import javax.sound.sampled.*;

class SamplePlayer extends Player implements Runnable, LineListener{
  Sample sample=null;
  Clip clip=null;
  boolean loop=false;
  Thread thread=null;

  SamplePlayer(Sample sample){
    super();
    this.sample=sample;
    this.clip=sample.clip;
    this.clip.addLineListener(this);
    sample.player=this;
    //add(this);
  }

  void play(){
    loop=false;
    thread=new Thread(this);
    thread.start();
  }
  void loop(){
    loop=true;
    thread=new Thread(this);
    thread.start();
  }
  public void run(){
    try {
      if(clip!=null){
        long time=clip.getMicrosecondLength();
	while(true){
          clip.setFramePosition(0);
	  clip.start();
          do{
	    try{ Thread.sleep(time); }catch(Exception e){break;}
	  }while(clip.isActive());
	  if(loop && thread!=null) continue;
	  break;
	}
	clip.stop();
        clip.removeLineListener(this);
	//del(this);
      } 
    } 
    catch(Exception e1){
      //System.err.println(e1); 
    }
  }

  void stop_playing(){
    thread=null;
    //del(this);
  }

  void kill(){
//  if(clip!=null){ clip.removeLineListener(this); clip.stop();}
    thread=null;
    //del(this);
  }

  public void update(LineEvent event) {
    //System.out.println("update: "+event);
  }

//  public void meta(MetaEvent event) {
//    //System.out.println("meta: "+event);
//  }
}
