/** * 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 { // Clip clip = AudioSystem.getClip(); Clip clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class)); clip.addLineListener(listener); clip.open(audioInputStream); try { clip.start(); listener.waitUntilDone(); } catch (InterruptedException e) { e.printStackTrace(); } finally { clip.close(); } audioInputStream.close(); }
/** Obtain the value of a default provider property. @param typeClass The type of the default provider property. This should be one of Receiver.class, Transmitter.class, Sequencer.class, Synthesizer.class, SourceDataLine.class, TargetDataLine.class, Clip.class or Port.class. @return The complete value of the property, if available. If the property is not set, null is returned. */ private static synchronized String getDefaultProvider(Class typeClass) { if (!SourceDataLine.class.equals(typeClass) && !TargetDataLine.class.equals(typeClass) && !Clip.class.equals(typeClass) && !Port.class.equals(typeClass) && !Receiver.class.equals(typeClass) && !Transmitter.class.equals(typeClass) && !Synthesizer.class.equals(typeClass) && !Sequencer.class.equals(typeClass)) { return null; } String name = typeClass.getName(); String value = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty(name)); if (value == null) { value = getProperties().getProperty(name); } if ("".equals(value)) { value = null; } return value; }
public ExtendedClip(JuggleMasterPro objPjuggleMasterPro, byte bytPsoundFileIndex) { this.bytGsoundFileIndex = bytPsoundFileIndex; try { final AudioInputStream objLaudioInputStream = AudioSystem.getAudioInputStream(new File(Strings.doConcat( objPjuggleMasterPro.strS_CODE_BASE, Constants.strS_FILE_NAME_A[Constants.intS_FILE_FOLDER_SOUNDS], objPjuggleMasterPro.chrGpathSeparator, Constants.strS_FILE_SOUND_NAME_A[bytPsoundFileIndex]))); final AudioFormat objLaudioFormat = objLaudioInputStream.getFormat(); final DataLine.Info objLdataLineInfo = new DataLine.Info(Clip.class, objLaudioFormat, (int) objLaudioInputStream.getFrameLength() * objLaudioFormat.getFrameSize()); this.objGclip = (Clip) AudioSystem.getLine(objLdataLineInfo); this.objGclip.open(objLaudioInputStream); } catch (final Throwable objPthrowable) { Tools.err("Error while initializing sound : ", Constants.strS_FILE_SOUND_NAME_A[bytPsoundFileIndex]); this.objGclip = null; } }
/** * The sound is load and play in a thread no slow down the engine. * */ @Override public void run() { try { InputStream in = new BufferedInputStream(this.getClass().getResourceAsStream(this.filename + ".wav")); Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(in)); if (this.loop){ clip.loop(Clip.LOOP_CONTINUOUSLY); } clip.start(); }catch (Exception e){ System.err.println(e); } }
/** Obtain the value of a default provider property. @param typeClass The type of the default provider property. This should be one of Receiver.class, Transmitter.class, Sequencer.class, Synthesizer.class, SourceDataLine.class, TargetDataLine.class, Clip.class or Port.class. @return The complete value of the property, if available. If the property is not set, null is returned. */ private static synchronized String getDefaultProvider(Class<?> typeClass) { if (!SourceDataLine.class.equals(typeClass) && !TargetDataLine.class.equals(typeClass) && !Clip.class.equals(typeClass) && !Port.class.equals(typeClass) && !Receiver.class.equals(typeClass) && !Transmitter.class.equals(typeClass) && !Synthesizer.class.equals(typeClass) && !Sequencer.class.equals(typeClass)) { return null; } String name = typeClass.getName(); String value = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty(name)); if (value == null) { value = getProperties().getProperty(name); } if ("".equals(value)) { value = null; } return value; }
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(); }
private static void doMixerClip(Mixer mixer, AudioFormat format) { if (mixer==null) return; try { System.out.println("Clip from mixer "+mixer+":"); System.out.println(" "+mixer.getMixerInfo()); DataLine.Info info = new DataLine.Info( Clip.class, format); if (mixer.isLineSupported(info)) { Clip clip = (Clip) mixer.getLine(info); doLine1(clip, format); } else { System.out.println(" - Line not supported"); } } catch (Throwable t) { System.out.println(" - Caught exception. Not failed."); System.out.println(" - "+t.toString()); } }
private synchronized void playSound(final String audioFileName) { if(isSoundEnabled) { try { Clip clip = AudioSystem.getClip(); InputStream inputStream = MainWindow.class.getResourceAsStream(audioFileName); if(inputStream != null) { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputStream); clip.open(audioInputStream); clip.start(); } else { System.out.println("Input stream not valid"); } } catch (Exception e) { e.printStackTrace(); } } }
/** * WAV files only * * @param name * Name to store sound as * @param file * Sound file */ public static void loadSound(String name, String file) { try { System.out.print("Loading sound file: \"" + file + "\" into clip: \"" + name + "\", "); BufferedInputStream in = new BufferedInputStream(SoundPlayer.class.getResourceAsStream(file)); AudioInputStream ain = AudioSystem.getAudioInputStream(in); Clip c = AudioSystem.getClip(); c.open(ain); c.setLoopPoints(0, -1); clips.put(name, c); ain.close(); in.close(); System.out.println("Done."); } catch (Exception e) { System.out.println("Failed. (" + e.getMessage() + ")"); } }
/** * 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(); }
/** * Destroys the MultiClip and releases all resources. */ public void destroy() { if (clips.size() > 0) { for (Clip c : clips) { c.stop(); c.flush(); c.close(); } extraClips -= clips.size() - 1; clips = new LinkedList<Clip>(); } audioData = null; if (audioIn != null) { try { audioIn.close(); } catch (IOException e) { explode(String.format("Could not close AudioInputStream for MultiClip %s.", name), e, DEFAULT_OPTIONS); } } }
/** * Mute the Clip (because destroying it, won't stop it) */ public void mute() { try { Clip c = getClip(); if (c == null) { return; } float val = (float) (Math.log(Float.MIN_VALUE) / Math.log(10.0) * 20.0); if (val < -80.0f) { val = -80.0f; } ((FloatControl) c.getControl(FloatControl.Type.MASTER_GAIN)).setValue(val); } catch (IllegalArgumentException ignored) { } catch (LineUnavailableException e) { e.printStackTrace(); } }
/** Play the audio clip when regular button is clicked. */ public void playButtonClickNormalSound() { try { String soundName = "regular_button_click_sound.wav"; AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile()); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.setFramePosition(0); clip.start(); } catch (Exception e) { } }
public static void main(String[] args) { new Thread(() -> { while (true) { int delay = (RANDOM.nextInt(MAX_DELAY_SECONDS - MIN_DELAY_SECONDS) + MIN_DELAY_SECONDS) * 1000; try ( ByteArrayInputStream bais = new ByteArrayInputStream(AUDIO_BYTES); AudioInputStream audioIn = AudioSystem.getAudioInputStream(bais); ) { Clip clip = AudioSystem.getClip(); clip.open(audioIn); Thread.currentThread().sleep(delay); clip.start(); } catch (InterruptedException | IOException | LineUnavailableException | UnsupportedAudioFileException ex) { ex.printStackTrace(); } } }).start(); }
private void play(String wavPath, float db) { if (!dnd && db > -40) { ClassLoader classLoader = getClass().getClassLoader(); try (AudioInputStream stream = AudioSystem.getAudioInputStream(classLoader.getResource(wavPath))) { Clip clip = AudioSystem.getClip(); clip.open(stream); if (db != 0.0) { FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(db); } clip.start(); } catch (Exception e) { logger.error("Cannot start playing wav file: ", e); } } }
/** Checks if a Mixer is appropriate. A Mixer is considered appropriate if it support the given line type. If isMixingRequired is true and the line type is an output one (SourceDataLine, Clip), the mixer is appropriate if it supports at least 2 (concurrent) lines of the given type. @return true if the mixer is considered appropriate according to the rules given above, false otherwise. */ private static boolean isAppropriateMixer(Mixer mixer, Line.Info lineInfo, boolean isMixingRequired) { if (! mixer.isLineSupported(lineInfo)) { return false; } Class lineClass = lineInfo.getLineClass(); if (isMixingRequired && (SourceDataLine.class.isAssignableFrom(lineClass) || Clip.class.isAssignableFrom(lineClass))) { int maxLines = mixer.getMaxLines(lineInfo); return ((maxLines == NOT_SPECIFIED) || (maxLines > 1)); } return true; }
/** * synchronized methods, suspends the excution * of other sounds until the first thread is * done.class */ private static synchronized void render(String filename) { new Thread(new Runnable() { public void run() { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( EventSounds.class.getResourceAsStream("resources/sounds/" + filename)); clip.open(inputStream); clip.start(); Thread.sleep(clip.getMicrosecondLength() / 1000); } catch (Exception error) { System.out.println(error.getMessage()); } } }).start(); }
/** * <strong><em>playSound</em></strong><br /><br /> * *  Plays a .wav audio file located in /res/audio/.<br /> *  <em>E.g.</em> <sub>audio</sub><br /><br /> *  File location would be: <sub>/res/audio/audio.wav</sub><br /> *  and would be played automatically. * * @param audio - File name. */ public void playSound(String audio){ try{ AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( getClass().getResource("/audio/"+audio+".wav")); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); clip.addLineListener(new LineListener() { @Override public void update(LineEvent arg0) { if(arg0.getFramePosition()==clip.getFrameLength()){ clip.close(); } } }); clips.put(audio, clip); }catch(Exception e){ e.printStackTrace(); } }
public static void main(String[] av) { if (av.length == 0) main(defSounds); else for (String a : av) { System.out.println("Playing " + a); try { URL snd = AudioPlay.class.getResource(a); if (snd == null) { System.err.println("Cannot getResource " + a); continue; } AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(snd); final Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); } catch (Exception e) { System.err.println(e); } } }
private void play() { byte[] out = new byte[HEADER_SIZE + 2 * samples.length]; for (int i = 0; i < HEADER_SIZE; i++) { out[i] = header[i]; } for (int i = 0; i < samples.length; i++) { int value = samples[i]; if (value < 0) { value = value + 65536; } out[HEADER_SIZE + 2 * i] = (byte)(value % 256); out[HEADER_SIZE + 2 * i + 1] = (byte)(value / 256); } try { Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(new ByteArrayInputStream(out))); clip.start(); } catch (Exception ex) { error(ex.getMessage()); } }
public static void playSoundFromStream(final Factory<InputStream> streamProducer) { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. @Override public void run() { try { Clip clip = AudioSystem.getClip(); InputStream stream = streamProducer.create(); if (!stream.markSupported()) stream = new BufferedInputStream(stream); AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream); clip.open(inputStream); clip.start(); } catch (Exception ignore) { LOG.info(ignore); } } },"play sound").start(); }
private static void playInThread(final Clip clip) { // run in new thread new Thread() { public void run() { try { clip.start(); while (clip.isActive()) { sleep(1000L); } clip.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } }.start(); }
public static synchronized void playSound(final String url) { new Thread(new Runnable() { @Override public void run() { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( BabystepsTimer.class.getResourceAsStream("/"+url)); clip.open(inputStream); clip.start(); } catch (Exception e) { System.err.println(e.getMessage()); } } }).start(); }
/** * Creates a new {@code PreloadedPlayback}. PreloadedPlayback objects will * always be created by their associated PreloadedAudio object. * <p> * IMPLEMENTATION NOTE: Originally, the fetching of a new {@code Line} was * done in the {@code run} method, however testing revealed that latency is * decreased if a {@code Line} is acquired ahead of time, here in the * constructor. * * @param audio * The {@code Audio} that created this {@code PreloadedPlayback}. * @param audioFormat * Specifies the particular arrangement of audio data. * @param audioBytes * Holds the audio data from which a {@code Clip} will be * created. * @param instanceID * The {@code instanceID} of this {@code PreloadedPlayback}. */ protected PreloadedPlayback(Audio audio, AudioFormat audioFormat, byte[] audioBytes, long instanceID) { super(audio, instanceID); DataLine.Info info = new DataLine.Info(Clip.class, audioFormat); try { clip = (Clip) AudioSystem.getLine(info); clip.open(audioFormat, audioBytes, 0, audioBytes.length); if (clip.isControlSupported(FloatControl.Type.MASTER_GAIN)) { volCtrl = (FloatControl) clip .getControl(FloatControl.Type.MASTER_GAIN); } else { logger.warning("Master-Gain control is not supported." + " Volume will be fixed at the default level."); } } catch (LineUnavailableException ex) { ex.printStackTrace(); } clip.addLineListener(this); }
@Override public void resume() { if (!clip.isRunning() && getState() == Playback.State.PAUSED) { logger.info("Resuming playback of \"" + audio.getFileName() + "\" instance " + instanceID); long loopsPlayed = clip.getMicrosecondPosition() / clip.getMicrosecondLength(); int loopsToGo = (numLoops - (int) loopsPlayed); if (loopsToGo <= 0 && !loopContinuously) { loopsToGo = 1; } else if (loopContinuously) { loopsToGo = Clip.LOOP_CONTINUOUSLY; } state = Playback.State.PLAYING; clip.loop(loopsToGo); } }
private Clip playAudioFile(URL soundURL) throws Exception { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundURL); BufferedInputStream bufferedInputStream = new BufferedInputStream(audioInputStream); AudioFormat af = audioInputStream.getFormat(); int size = (int) (af.getFrameSize() * audioInputStream.getFrameLength()); byte[] audio = new byte[size]; DataLine.Info info = new DataLine.Info(Clip.class, af, size); bufferedInputStream.read(audio, 0, size); Clip clip = (Clip) AudioSystem.getLine(info); clip.open(af, audio, 0, size); clip.start(); bufferedInputStream.close(); return clip; }
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; }
public EventCountdown() { Application app = Application.getInstance(); String fileName = app.getProperty(Application.PropertyCountdownSound, (String) null); countdownMillis = (long) (app.getProperty(Application.PropertyCountdownSeconds, (Float) 0.0f) * 1000f); vs = app.getProperty(Application.PropertyVS, Application.DefaultVS); if (fileName != null && countdownMillis > 0) { try { sound = new File(fileName); AudioInputStream inputStream = AudioSystem.getAudioInputStream(sound); AudioFormat format = inputStream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); clip = (Clip) AudioSystem.getLine(info); } catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) { LOG.error("could not open countdown sound file", e); } } }
/** * Performs message received sound, if sound setting allows it. */ public void messageSound(){ if(sound){ new Thread(() -> { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( (getClass().getResource("/Media/MSNsound.wav"))); clip.open(inputStream); clip.start(); } catch (Exception e) { // System.err.println(e.getMessage()); } }).start(); } }
private void playIt(InputStream inputStream) throws IOException, UnsupportedAudioFileException, LineUnavailableException, InterruptedException, IllegalArgumentException { AudioListener listener = new AudioListener(); try { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(inputStream)); AudioFormat format = audioInputStream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); Clip clip = (Clip) AudioSystem.getLine(info); clip.addLineListener(listener); clip.open(audioInputStream); try { clip.start(); listener.waitUntilDone(); } finally { clip.close(); } } finally { inputStream.close(); } }
private void setClip(File music){ // Create clip from file try { System.gc(); af = music; // af is wave file from disk stream = AudioSystem.getAudioInputStream(music); // Creating a input stream format = stream.getFormat(); rawData = new byte[(int)stream.getFrameLength()*2*format.getChannels()]; // Define byte array size IOUtils.read(AudioSystem.getAudioInputStream(af), rawData); // Read all data from clip to array info = new DataLine.Info(Clip.class, format); clip = (Clip)AudioSystem.getLine(info); // Creating clip clip.open(stream); // Opening clip with stream System.gc(); } catch (Exception e) { e.printStackTrace(); } }
@Override public void invokeAction(final PiAction action) throws RaspberryPiAppException { final String soundFile = baseSoundDirectory + action.getValue(); LOGGER.debug("Playing sound file: '{}'", soundFile); try { final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( new File(soundFile)); final Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); // play at maximum volume final FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(gainControl.getMaximum()); clip.start(); } catch (Exception e) { throw new RaspberryPiAppException(e.getMessage(), e); } }
/** * Opens a new sound and replaces the old one. If object is set to loop the sound (isLoop = true) then it will loop * * @param file - the file path and name of the audio to play */ public void open(File file) { try { clip.stop(); clip.close(); audio = AudioSystem.getAudioInputStream(file); clip.open(audio); volumeControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN); clip.start(); if(isLoop) clip.loop(Clip.LOOP_CONTINUOUSLY); else clip.loop(0); } catch(UnsupportedAudioFileException uae) { System.out.println(uae); } catch(IOException ioe) { System.out.println(ioe); System.out.println(file); } catch(LineUnavailableException lua) { System.out.println(lua); } }
/** * Will open a new file for a certain volume. * * @param file - File of audio to open * @param volume - Volume of audio to play from 100 to 0 */ public void open(File file, float volume) { try { clip.stop(); clip.close(); audio = AudioSystem.getAudioInputStream(file); clip.open(audio); volumeControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN); setVolume(volume); clip.start(); if(isLoop) clip.loop(Clip.LOOP_CONTINUOUSLY); else clip.loop(0); } catch(UnsupportedAudioFileException uae) { System.out.println(uae); } catch(IOException ioe) { System.out.println(ioe); System.out.println(file); } catch(LineUnavailableException lua) { System.out.println(lua); } }