package myplayer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Decoder;
import javazoom.jl.decoder.Header;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.AudioDevice;
import javazoom.jl.player.FactoryRegistry;
import javazoom.jl.player.Player;
public class MyPlayer extends Player {
/**
* Aggiunge il metodo pause alla classe Player, oltre a lanciare eventi personalizzati
* durante la riproduzione e consente inoltre la riproduzione da un punto qualsiasi
* del flusso dati.
* Conserva inoltre le dimensioni del file, intese come numero di frames.
* */
public MyPlayer(Mp3InputStream fileIn) throws JavaLayerException {
super(fileIn);
fileStream = fileIn;
bitstream = new Bitstream(fileStream);
maxFramesNumber = getFramesCount(fileIn.getName());
}
public void play(int start, int end) throws JavaLayerException {
isActive = true;
while (currentFrame < start - corrFactor) {
skipFrame(bitstream);
currentFrame++;
}
audioDevice = FactoryRegistry.systemRegistry().createAudioDevice();
decoder = new Decoder();
audioDevice.open(decoder);
while(isActive && currentFrame < maxFramesNumber) {
decodeFrame();
currentFrame++;
if(lst != null){
lst.onFrameRead(currentFrame);
}
}
if (audioDevice != null) {
audioDevice.flush();
synchronized (this) {
super.close();
}
}
if(lst != null && currentFrame >= maxFramesNumber)
lst.onFinish();
}
public void stop() {
isActive = false;
}
public void addListener(PlayerListener p) {
lst = p;
}
@Override
public int getPosition() {
return currentFrame;
}
public int getFrameNumber() {
return maxFramesNumber;
}
private boolean skipFrame(Bitstream stream) throws BitstreamException {
Header header = stream.readFrame();
if (header != null) {
stream.closeFrame();
return true;
} else {
return false;
}
}
private int getFramesCount(String name) {
Bitstream tmp = new Bitstream(getInputStream(name));
int c = 0;
try {
while (skipFrame(tmp))
c++;
} catch (BitstreamException e1) {
e1.printStackTrace();
}
try {
tmp.close();
} catch (BitstreamException e) {
e.printStackTrace();
}
return c;
}
private InputStream getInputStream(String name) {
try {
return new FileInputStream(name);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
private int maxFramesNumber;
//private Logger logger = Logger.getLogger("global");
private static final int corrFactor = 20;
private Bitstream bitstream;
private AudioDevice audioDevice;
private Decoder decoder;
private Mp3InputStream fileStream;
private int currentFrame;
private boolean isActive;
private PlayerListener lst;
}