Java Code Examples for javax.sound.sampled.Clip#addLineListener()

The following examples show how to use javax.sound.sampled.Clip#addLineListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Utils.java    From ripme with MIT License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 2
Source File: IsRunningHang.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example 3
Source File: MultiClip.java    From opsu-dance with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 4
Source File: Sound.java    From WorldGrower with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: UI.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
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();
	}
}
 
Example 6
Source File: MultiClip.java    From opsu with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 7
Source File: Demo_MultichannelAudio_NativeMultipleSoundcard.java    From haxademic with MIT License 6 votes vote down vote up
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);
    }
}
 
Example 8
Source File: soundPlayer.java    From Game with GNU General Public License v3.0 5 votes vote down vote up
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") + ')');
	}
}
 
Example 9
Source File: DefaultSoundEffect.java    From petscii-bbs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param clip an audio clip
 */
public DefaultSoundEffect(final Clip clip) {
  
  super();
  this.clip = clip;
  listeners = new ArrayList<SoundStopListener>();
  clip.addLineListener(this);
}
 
Example 10
Source File: ClipLinuxCrash2.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: ClipPlayer.java    From FxDock with Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 12
Source File: TelegraphSound.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 13
Source File: bug6251460.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
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.");
}
 
Example 14
Source File: ClipLinuxCrash.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
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);
}