下面列出了javax.sound.sampled.Clip#addLineListener ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Plays a sound from a file.
*
* @param filename Path to the sound file
*/
public static void playSound(String filename) {
URL resource = ClassLoader.getSystemClassLoader().getResource(filename);
try {
final Clip clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class));
clip.addLineListener(event -> {
if (event.getType() == LineEvent.Type.STOP) {
clip.close();
}
});
clip.open(AudioSystem.getAudioInputStream(resource));
clip.start();
} catch (Exception e) {
LOGGER.error("Failed to play sound " + filename, e);
}
}
private static void test(final AudioFormat format, final byte[] data)
throws Exception {
final Line.Info info = new DataLine.Info(Clip.class, format);
final Clip clip = (Clip) AudioSystem.getLine(info);
go = new CountDownLatch(1);
clip.addLineListener(event -> {
if (event.getType().equals(LineEvent.Type.START)) {
go.countDown();
}
});
clip.open(format, data, 0, data.length);
clip.start();
go.await();
while (clip.isRunning()) {
// This loop should not hang
}
while (clip.isActive()) {
// This loop should not hang
}
clip.close();
}
/**
* Plays the clip with the specified volume.
* @param volume the volume the play at
* @param listener the line listener
* @throws LineUnavailableException if a clip object is not available or
* if the line cannot be opened due to resource restrictions
*/
public void start(float volume, LineListener listener) throws LineUnavailableException {
Clip clip = getClip();
if (clip == null)
return;
// PulseAudio does not support Master Gain
if (clip.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
// set volume
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
float dB = (float) (Math.log(volume) / Math.log(10.0) * 20.0);
gainControl.setValue(dB);
}
if (listener != null)
clip.addLineListener(listener);
clip.setFramePosition(0);
clip.start();
}
private Clip openClip(boolean closeAfterPlaying) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
AudioInputStream audioStream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(audioFilePath));
DataLine.Info info = getLineInfo(audioStream);
Clip audioClip = (Clip) AudioSystem.getLine(info);
if (closeAfterPlaying) {
audioClip.addLineListener(new LineListener() {
@Override
public void update(LineEvent myLineEvent) {
if (myLineEvent.getType() == LineEvent.Type.STOP)
audioClip.close();
}
});
}
audioClip.open(audioStream);
return audioClip;
}
private void playSirenSound() {
try {
File soundFile = new File(sirenFile);
AudioInputStream soundIn = AudioSystem.getAudioInputStream(soundFile);
AudioFormat format = soundIn.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
soundOn = false;
}
}
});
clip.open(soundIn);
clip.start();
soundOn = true;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Plays the clip with the specified volume.
* @param volume the volume the play at
* @param listener the line listener
* @throws LineUnavailableException if a clip object is not available or
* if the line cannot be opened due to resource restrictions
*/
public void start(float volume, LineListener listener) throws LineUnavailableException {
Clip clip = getClip();
if (clip == null)
return;
// PulseAudio does not support Master Gain
if (clip.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
// set volume
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
float dB = (float) (Math.log(volume) / Math.log(10.0) * 20.0);
gainControl.setValue(Utils.clamp(dB, gainControl.getMinimum(), gainControl.getMaximum()));
} else if (clip.isControlSupported(FloatControl.Type.VOLUME)) {
// The docs don't mention what unit "volume" is supposed to be,
// but for PulseAudio it seems to be amplitude
FloatControl volumeControl = (FloatControl) clip.getControl(FloatControl.Type.VOLUME);
float amplitude = (float) Math.sqrt(volume) * volumeControl.getMaximum();
volumeControl.setValue(Utils.clamp(amplitude, volumeControl.getMinimum(), volumeControl.getMaximum()));
}
if (listener != null)
clip.addLineListener(listener);
clip.setFramePosition(0);
clip.start();
}
public void play(File file, Clip clip) {
try {
// get a mixer and play clip like that
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
clip.close();
}
}
});
clip.open(AudioSystem.getAudioInputStream(file));
clip.start();
} catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
public static void playSoundFile(String key) {
try {
if (!mudclient.optionSoundDisabled) {
File sound = mudclient.soundCache.get(key + ".wav");
if (sound == null)
return;
try {
// PC sound code:
final Clip clip = AudioSystem.getClip();
clip.addLineListener(myLineEvent -> {
if (myLineEvent.getType() == LineEvent.Type.STOP)
clip.close();
});
clip.open(AudioSystem.getAudioInputStream(sound));
clip.start();
// Android sound code:
//int dataLength = DataOperations.getDataFileLength(key + ".pcm", soundData);
//int offset = DataOperations.getDataFileOffset(key + ".pcm", soundData);
//clientPort.playSound(soundData, offset, dataLength);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (RuntimeException var6) {
throw GenUtil.makeThrowable(var6, "client.SC(" + "dummy" + ',' + (key != null ? "{...}" : "null") + ')');
}
}
/**
* Constructor.
*
* @param clip an audio clip
*/
public DefaultSoundEffect(final Clip clip) {
super();
this.clip = clip;
listeners = new ArrayList<SoundStopListener>();
clip.addLineListener(this);
}
public long start() throws Exception {
AudioFormat format = new AudioFormat(44100, 16, 2, true, false);
if (addLen) {
staticLen+=(int) (staticLen/5)+1000;
} else {
staticLen-=(int) (staticLen/5)+1000;
}
if (staticLen>8*44100*4) {
staticLen = 8*44100*4;
addLen=!addLen;
}
if (staticLen<1000) {
staticLen = 1000;
addLen=!addLen;
}
int len = staticLen;
len -= (len % 4);
out(" Test program: preparing to play back "+len+" bytes == "+bytes2Ms(len, format)+"ms audio...");
byte[] fakedata=new byte[len];
InputStream is = new ByteArrayInputStream(fakedata);
AudioInputStream ais = new AudioInputStream(is, format, fakedata.length/format.getFrameSize());
DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat());
clip = (Clip) AudioSystem.getLine(info);
clip.addLineListener(this);
out(" Test program: opening clip="+((clip==null)?"null":clip.toString()));
clip.open(ais);
ais.close();
out(" Test program: starting clip="+((clip==null)?"null":clip.toString()));
clip.start();
return bytes2Ms(fakedata.length, format);
}
public static void play(InputStream in)
{
try
{
AudioInputStream stream = AudioSystem.getAudioInputStream(in);
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
final Clip clip = (Clip)AudioSystem.getLine(info);
clip.addLineListener(new LineListener()
{
public void update(LineEvent ev)
{
LineEvent.Type t = ev.getType();
if(t == LineEvent.Type.STOP)
{
clip.close();
}
}
});
clip.open(stream);
clip.start();
}
catch(Exception e)
{
Log.err(e);
}
}
/**
* This method allows to actually play the sound provided from the
* {@link #audioInputStream}
*
* @throws LineUnavailableException
* if the {@link Clip} object can't be created
* @throws IOException
* if the audio file can't be find
*/
protected void play() throws LineUnavailableException, IOException {
final Clip clip = AudioSystem.getClip();
clip.addLineListener(listener);
clip.open(audioInputStream);
try {
clip.start();
listener.waitUntilDone();
} catch (final InterruptedException e) {
e.printStackTrace();
} finally {
clip.close();
}
audioInputStream.close();
}
static protected void test()
throws LineUnavailableException, InterruptedException {
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
final MutableBoolean clipStoppedEvent = new MutableBoolean(false);
clip.addLineListener(new LineListener() {
@Override
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
synchronized (clipStoppedEvent) {
clipStoppedEvent.value = true;
clipStoppedEvent.notifyAll();
}
}
}
});
clip.open(format, soundData, 0, soundData.length);
long lengthClip = clip.getMicrosecondLength() / 1000;
log("Clip length " + lengthClip + " ms");
log("Playing...");
for (int i=1; i<=LOOP_COUNT; i++) {
long startTime = currentTimeMillis();
log(" Loop " + i);
clip.start();
synchronized (clipStoppedEvent) {
while (!clipStoppedEvent.value) {
clipStoppedEvent.wait();
}
clipStoppedEvent.value = false;
}
long endTime = currentTimeMillis();
long lengthPlayed = endTime - startTime;
if (lengthClip > lengthPlayed + 20) {
log(" ERR: Looks like sound didn't play: played " + lengthPlayed + " ms instead " + lengthClip);
countErrors++;
} else {
log(" OK: played " + lengthPlayed + " ms");
}
clip.setFramePosition(0);
}
log("Played " + LOOP_COUNT + " times, " + countErrors + " errors detected.");
}
public static long start() throws Exception {
AudioFormat fmt = new AudioFormat(44100, 16, 2, true, false);
if (addLen) {
staticLen += (int) (staticLen / 5) + 1000;
} else {
staticLen -= (int) (staticLen / 5) + 1000;
}
if (staticLen > 8 * 44100 * 4) {
staticLen = 8 * 44100 * 4;
addLen = !addLen;
}
if (staticLen < 1000) {
staticLen = 1000;
addLen = !addLen;
}
int len = staticLen;
len -= (len % 4);
byte[] fakedata = new byte[len];
InputStream is = new ByteArrayInputStream(fakedata);
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
44100, 16, 2, 4, 44100, false);
AudioInputStream ais = new AudioInputStream(is, format, fakedata.length
/ format.getFrameSize());
out(" preparing to play back " + len + " bytes == " + bytes2Ms(len,
format)
+ "ms audio...");
DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat());
clip = (Clip) AudioSystem.getLine(info);
clip.addLineListener(new LineListener() {
public void update(LineEvent e) {
if (e.getType() == LineEvent.Type.STOP) {
out(" calling close() from event dispatcher thread");
((Clip) e.getSource()).close();
} else if (e.getType() == LineEvent.Type.CLOSE) {
}
}
});
out(" opening...");
try {
clip.open(ais);
} catch (Throwable t) {
t.printStackTrace();
clip.close();
clip = null;
}
ais.close();
if (clip != null) {
out(" starting...");
clip.start();
}
return bytes2Ms(fakedata.length, format);
}