下面列出了javax.sound.sampled.Clip#open ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Clip GetAudioClip(String path)
{
File audioFile = new File(path);
if (!audioFile.exists())
{
return null;
}
try (AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile))
{
Clip audioClip = AudioSystem.getClip();
audioClip.open(audioStream);
FloatControl gainControl = (FloatControl) audioClip.getControl(FloatControl.Type.MASTER_GAIN);
float gainValue = (((float) config.volume()) * 40f / 100f) - 35f;
gainControl.setValue(gainValue);
return audioClip;
}
catch (IOException | LineUnavailableException | UnsupportedAudioFileException e)
{
log.warn("Error opening audiostream from " + audioFile, e);
return null;
}
}
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);
}
}
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();
}
}
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();
}
static public void playSound(String url) {
if (url.isEmpty()) return;
try {
Clip clip = AudioSystem.getClip();
BufferedInputStream x = new BufferedInputStream(new FileInputStream(url));
AudioInputStream inputStream = AudioSystem.getAudioInputStream(x);
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
public static void play(Mixer mixer) {
int res = 0;
try {
println("Getting clip from mixer...");
source = (Clip) mixer.getLine(info);
println("Opening clip...");
source.open(audioFormat, audioData, 0, audioData.length);
println("Starting clip...");
source.loop(Clip.LOOP_CONTINUOUSLY);
println("Now open your ears:");
println("- if you hear a sine wave playing,");
println(" listen carefully if you can hear clicks.");
println(" If no, the bug is fixed.");
println("- if you don't hear anything, it's possible");
println(" that this mixer is not connected to an ");
println(" amplifier, or that its volume is set to 0");
key();
} catch (IllegalArgumentException iae) {
println("IllegalArgumentException: "+iae.getMessage());
println("Sound device cannot handle this audio format.");
println("ERROR: Test environment not correctly set up.");
if (source!=null) {
source.close();
source = null;
}
return;
} catch (LineUnavailableException lue) {
println("LineUnavailableException: "+lue.getMessage());
println("This is normal for some mixers.");
} catch (Exception e) {
println("Unexpected Exception: "+e.toString());
}
if (source != null) {
println("Stopping...");
source.stop();
println("Closing...");
source.close();
println("Closed.");
source = null;
}
}
private static boolean doMixerClip(Mixer mixer, AudioFormat format) {
if (mixer==null) return false;
try {
System.out.println("Trying mixer "+mixer+":");
DataLine.Info info = new DataLine.Info(
Clip.class,
format,
(int) samplerate);
Clip clip = (Clip) mixer.getLine(info);
System.out.println(" - got clip: "+clip);
System.out.println(" - open with format "+format);
clip.open(format, buffer, 0, buffer.length);
System.out.println(" - playing...");
clip.start();
System.out.println(" - waiting while it's active...");
while (clip.isActive())
Thread.sleep(100);
System.out.println(" - waiting 100millis");
Thread.sleep(100);
System.out.println(" - drain1");
clip.drain();
System.out.println(" - drain2");
clip.drain();
System.out.println(" - stop");
clip.stop();
System.out.println(" - close");
clip.close();
System.out.println(" - closed");
} catch (Throwable t) {
System.out.println(" - Caught exception. Not failed.");
System.out.println(" - "+t.toString());
return false;
}
return true;
}
/**
* 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();
}
private void loadClip() {
clipLoaded = true;
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(The5zigMod.getModDirectory(),
"media/" + The5zigMod.getDataManager().getUniqueId().toString() + "/" + ((ConversationChat) getMessage().getConversation()).getFriendUUID().toString() + "/" +
getAudioData().getHash()));
clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class));
clip.open(audioInputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Clip createClip() throws LineUnavailableException {
AudioFormat format =
new AudioFormat(PCM_SIGNED, 44100, 8, 1, 1, 44100, false);
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(format, new byte[2], 0, 2);
return clip;
}
static Clip createClip(final AudioInputStream inputStream) {
Clip clip = null;
try {
clip = AudioSystem.getClip();
clip.open(inputStream);
} catch (final LineUnavailableException | IOException e) {
e.printStackTrace();
}
return clip;
}
public static synchronized Clip playback(AudioInputStream in, float addVolume) {
try {
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
AudioInputStream ain = AudioSystem.getAudioInputStream(decodedFormat, in);
DataLine.Info info = new DataLine.Info(Clip.class, decodedFormat);
// https://stackoverflow.com/questions/25564980/java-use-a-clip-and-a-try-with-resources-block-which-results-with-no-sound
final Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(ain);
// Input stream must be closed, or else some thread is still running when application is exited.
in.close();
ain.close();
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(addVolume); // Add volume by decibels.
return clip;
} catch (Exception e) {
logger.debug(e.toString());
return null;
}
}
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);
}
}
private void playSound(String soundName) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
AudioFormat format = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(audioInputStream);
clip.start();
} catch (IllegalArgumentException | IOException | LineUnavailableException | UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
private static Clip createClip() throws LineUnavailableException {
AudioFormat format =
new AudioFormat(PCM_SIGNED, 44100, 8, 1, 1, 44100, false);
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(format, new byte[2], 0, 2);
return clip;
}
private static void doMixerClip(Mixer mixer) throws Exception {
boolean waitedEnough=false;
try {
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) mixer.getLine(info);
clip.open(format, soundData, 0, soundData.length);
// sanity
if (clip.getMicrosecondLength()/1000 < 9900) {
throw new Exception("clip's microsecond length should be at least 9900000, but it is "+clip.getMicrosecondLength());
}
long start = System.currentTimeMillis();
System.out.println(" ---------- start --------");
clip.start();
// give time to actually start it. ALSA implementation needs that...
Thread.sleep(300);
System.out.println("drain ... ");
clip.drain();
long elapsedTime = System.currentTimeMillis() - start;
System.out.println("close ... ");
clip.close();
System.out.println("... done");
System.out.println("Playback duration: "+elapsedTime+" milliseconds.");
waitedEnough = elapsedTime >= ((clip.getMicrosecondLength() / 1000) - TOLERANCE_MS);
} catch (Throwable t) {
System.out.println(" - Caught exception. Not failed.");
System.out.println(" - "+t.toString());
return;
}
if (!waitedEnough) {
throw new Exception("Drain did not wait long enough to play entire clip.");
}
successfulTests++;
}
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);
}
private static Clip createClip() throws LineUnavailableException {
AudioFormat format =
new AudioFormat(PCM_SIGNED, 44100, 8, 1, 1, 44100, false);
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(format, new byte[2], 0, 2);
return clip;
}
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);
}