Example usage for javax.sound.sampled Clip open

List of usage examples for javax.sound.sampled Clip open

Introduction

In this page you can find the example usage for javax.sound.sampled Clip open.

Prototype

void open(AudioInputStream stream) throws LineUnavailableException, IOException;

Source Link

Document

Opens the clip with the format and audio data present in the provided audio input stream.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile"));

    // From URL/*from   w  ww .  ja  v a  2s.  c  o m*/
    // stream = AudioSystem.getAudioInputStream(new URL(
    // "http://hostname/audiofile"));

    AudioFormat format = stream.getFormat();
    if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(),
                format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2,
                format.getFrameRate(), true); // big endian
        stream = AudioSystem.getAudioInputStream(format, stream);
    }

    DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
            ((int) stream.getFrameLength() * format.getFrameSize()));
    Clip clip = (Clip) AudioSystem.getLine(info);

    clip.open(stream);

    clip.start();
}

From source file:ClipTest.java

public static void main(String[] args) throws Exception {

    // specify the sound to play
    // (assuming the sound can be played by the audio system)
    File soundFile = new File("../sounds/voice.wav");
    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);

    // load the sound into memory (a Clip)
    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
    Clip clip = (Clip) AudioSystem.getLine(info);
    clip.open(sound);

    // due to bug in Java Sound, explicitly exit the VM when
    // the sound has stopped.
    clip.addLineListener(new LineListener() {
        public void update(LineEvent event) {
            if (event.getType() == LineEvent.Type.STOP) {
                event.getLine().close();
                System.exit(0);/*w  ww . jav a 2  s  . c  o m*/
            }
        }
    });

    // play the sound clip
    clip.start();
}

From source file:org.openhab.io.multimedia.actions.Audio.java

@ActionDoc(text = "plays a sound from the sounds folder")
static public void playSound(
        @ParamDoc(name = "filename", text = "the filename with extension") String filename) {
    try {//from  www  .  j a v a  2s  .co m
        InputStream is = new FileInputStream(SOUND_DIR + File.separator + filename);
        if (filename.toLowerCase().endsWith(".mp3")) {
            Player player = new Player(is);
            playInThread(player);
        } else {
            AudioInputStream ais = AudioSystem.getAudioInputStream(is);
            Clip clip = AudioSystem.getClip();
            clip.open(ais);
            playInThread(clip);
        }
    } catch (FileNotFoundException e) {
        logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() });
    } catch (JavaLayerException e) {
        logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() });
    } catch (UnsupportedAudioFileException e) {
        logger.error("Format of sound file '{}' is not supported: {}",
                new String[] { filename, e.getMessage() });
    } catch (IOException e) {
        logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() });
    } catch (LineUnavailableException e) {
        logger.error("Cannot play sound '{}': {}", new String[] { filename, e.getMessage() });
    }
}

From source file:org.scantegrity.scanner.Scanner.java

private static void playAudioClip(int p_numTimes) {
    /*/*from w  ww.  ja  va  2s . c  om*/
     * Threaded Code....sigsegv when run
     * /
    if(c_audioThread != null && c_audioThread.isAlive()) {
       try {
    c_audioThread.join(2000);
       } catch (InterruptedException e) {
    c_log.log(Level.SEVERE, "Could not wait for previous sound thread.");
       }
    }
            
    c_audioThread = new Thread(new AudioFile(c_soundFile, p_numTimes));
    c_audioThread.start();
    /* 
     * End threaded Code
     */

    AudioInputStream l_stream = null;
    try {
        l_stream = AudioSystem.getAudioInputStream(new File(c_soundFileName));
    } catch (UnsupportedAudioFileException e_uaf) {
        c_log.log(Level.WARNING, "Unsupported Audio File");
        return;
    } catch (IOException e1) {
        c_log.log(Level.WARNING, "Could not Open Audio File");
        return;
    }

    AudioFormat l_format = l_stream.getFormat();
    Clip l_dataLine = null;
    DataLine.Info l_info = new DataLine.Info(Clip.class, l_format);

    if (!AudioSystem.isLineSupported(l_info)) {
        c_log.log(Level.WARNING, "Audio Line is not supported");
    }

    try {
        l_dataLine = (Clip) AudioSystem.getLine(l_info);
        l_dataLine.open(l_stream);
    } catch (LineUnavailableException ex) {
        c_log.log(Level.WARNING, "Audio Line is unavailable.");
    } catch (IOException e) {
        c_log.log(Level.WARNING, "Cannot playback Audio, IO Exception.");
    }

    l_dataLine.loop(p_numTimes);

    try {
        Thread.sleep(160 * (p_numTimes + 1));
    } catch (InterruptedException e) {
        c_log.log(Level.WARNING, "Could not sleep the audio player thread.");
    }

    l_dataLine.close();
}

From source file:com.jostrobin.battleships.view.sound.DefaultSoundEffects.java

private void playSound(final String path) {
    if (enabled) {

        InputStream is = ClassLoader.getSystemResourceAsStream(path);
        AudioInputStream audioInputStream = null;
        try {//from  ww w  .ja v a  2s . c om
            audioInputStream = AudioSystem.getAudioInputStream(is);
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();
            while (clip.isRunning()) {
                Thread.sleep(10);
            }
        } catch (Exception e) {
            logger.warn("Could not play sound effect", e);
        } finally {
            IOUtils.closeSilently(is, audioInputStream);
        }
    }
}

From source file:edu.tsinghua.lumaqq.Sounder.java

/**
 * /*  w  w w  . j  av a  2  s.  c o  m*/
 * @param filename
 * @return
 */
private boolean loadSound(String filename) {
    // ??
    File file = new File(filename);
    try {
        currentSound = AudioSystem.getAudioInputStream(file);
    } catch (Exception e) {
        try {
            FileInputStream is = new FileInputStream(file);
            currentSound = new BufferedInputStream(is, 1024);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            currentSound = null;
            return false;
        }
    }

    // ??????
    if (currentSound instanceof AudioInputStream) {
        try {
            AudioInputStream stream = (AudioInputStream) currentSound;
            AudioFormat format = stream.getFormat();

            // ?? ALAW/ULAW ?  ALAW/ULAW ?? PCM                
            if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
                    || (format.getEncoding() == AudioFormat.Encoding.ALAW)) {
                AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(),
                        format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2,
                        format.getFrameRate(), true);
                stream = AudioSystem.getAudioInputStream(tmp, stream);
                format = tmp;
            }
            DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
                    ((int) stream.getFrameLength() * format.getFrameSize()));

            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.open(stream);
            currentSound = clip;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            currentSound = null;
            return false;
        }
    } else if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream) {
        try {
            sequencer.open();
            if (currentSound instanceof Sequence) {
                sequencer.setSequence((Sequence) currentSound);
            } else {
                sequencer.setSequence((BufferedInputStream) currentSound);
            }
            log.trace("Sequence Created");
        } catch (InvalidMidiDataException imde) {
            log.error("???");
            currentSound = null;
            return false;
        } catch (Exception ex) {
            log.error(ex.getMessage());
            currentSound = null;
            return false;
        }
    }

    return true;
}

From source file:SimpleSoundPlayer.java

public boolean loadSound(Object object) {
    duration = 0.0;//from   w  w  w  .j a va  2  s . co  m

    currentName = ((File) object).getName();
    try {
        currentSound = AudioSystem.getAudioInputStream((File) object);
    } catch (Exception e1) {
        try {
            FileInputStream is = new FileInputStream((File) object);
            currentSound = new BufferedInputStream(is, 1024);
        } catch (Exception e3) {
            e3.printStackTrace();
            currentSound = null;
            return false;
        }
        // }
    }

    // user pressed stop or changed tabs while loading
    if (sequencer == null) {
        currentSound = null;
        return false;
    }

    if (currentSound instanceof AudioInputStream) {
        try {
            AudioInputStream stream = (AudioInputStream) currentSound;
            AudioFormat format = stream.getFormat();

            /**
             * we can't yet open the device for ALAW/ULAW playback, convert
             * ALAW/ULAW to PCM
             */

            if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
                    || (format.getEncoding() == AudioFormat.Encoding.ALAW)) {
                AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(),
                        format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2,
                        format.getFrameRate(), true);
                stream = AudioSystem.getAudioInputStream(tmp, stream);
                format = tmp;
            }
            DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
                    ((int) stream.getFrameLength() * format.getFrameSize()));

            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.addLineListener(this);
            clip.open(stream);
            currentSound = clip;
            // seekSlider.setMaximum((int) stream.getFrameLength());
        } catch (Exception ex) {
            ex.printStackTrace();
            currentSound = null;
            return false;
        }
    } else if (currentSound instanceof Sequence || currentSound instanceof BufferedInputStream) {
        try {
            sequencer.open();
            if (currentSound instanceof Sequence) {
                sequencer.setSequence((Sequence) currentSound);
            } else {
                sequencer.setSequence((BufferedInputStream) currentSound);
            }

        } catch (InvalidMidiDataException imde) {
            System.out.println("Unsupported audio file.");
            currentSound = null;
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            currentSound = null;
            return false;
        }
    }

    duration = getDuration();

    return true;
}

From source file:net.sf.firemox.tools.MToolKit.java

/**
 * loadClip loads the sound-file into a clip.
 * //w  w w . j av  a  2s.co m
 * @param soundFile
 *          file to be loaded and played.
 */
public static void loadClip(String soundFile) {
    AudioFormat audioFormat = null;
    AudioInputStream actionIS = null;
    try {
        // actionIS = AudioSystem.getAudioInputStream(input); // Does not work !
        actionIS = AudioSystem.getAudioInputStream(MToolKit.getFile(MToolKit.getSoundFile(soundFile)));
        AudioFormat.Encoding targetEncoding = AudioFormat.Encoding.PCM_SIGNED;
        actionIS = AudioSystem.getAudioInputStream(targetEncoding, actionIS);
        audioFormat = actionIS.getFormat();

    } catch (UnsupportedAudioFileException afex) {
        Log.error(afex);
    } catch (IOException ioe) {

        if (ioe.getMessage().equalsIgnoreCase("mark/reset not supported")) { // Ignore
            Log.error("IOException ignored.");
        }
        Log.error(ioe.getStackTrace());
    }

    // define the required attributes for our line,
    // and make sure a compatible line is supported.

    // get the source data line for play back.
    DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
    if (!AudioSystem.isLineSupported(info)) {
        Log.error("LineCtrl matching " + info + " not supported.");
        return;
    }

    // Open the source data line for play back.
    try {
        Clip clip = null;
        try {
            Clip.Info info2 = new Clip.Info(Clip.class, audioFormat);
            clip = (Clip) AudioSystem.getLine(info2);
            clip.open(actionIS);
            clip.start();
        } catch (IOException ioe) {
            Log.error(ioe);
        }
    } catch (LineUnavailableException ex) {
        Log.error("Unable to open the line: " + ex);
        return;
    }
}

From source file:la2launcher.MainFrame.java

public static synchronized void playSound() {
    new Thread(new Runnable() {
        // The wrapper thread is unnecessary, unless it blocks on the
        // Clip finishing; see comments.
        public void run() {
            try {
                Clip clip = AudioSystem.getClip();
                AudioInputStream inputStream = AudioSystem.getAudioInputStream(
                        new BufferedInputStream(this.getClass().getResourceAsStream("alert.vaw")));
                clip.open(inputStream);
                //clip.start();
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }//from  w  ww  .  j a va  2s  .c o m
        }
    }).start();
}

From source file:ca.sqlpower.dao.SPPersisterListener.java

/**
 * Does the actual commit when the transaction count reaches 0. This ensures
 * the persist calls are contained in a transaction if a lone change comes
 * through. This also allows us to roll back changes if an exception comes
 * from the server./*www .j a  v  a 2s.  co  m*/
 * 
 * @throws SPPersistenceException
 */
private void commit() throws SPPersistenceException {
    logger.debug("commit(): transactionCount = " + transactionCount);
    if (transactionCount == 1) {
        try {
            logger.debug("Calling commit...");
            //If nothing actually changed in the transaction do not send
            //the begin and commit to reduce server traffic.
            if (objectsToRemove.isEmpty() && persistedObjects.isEmpty() && persistedProperties.isEmpty())
                return;
            target.begin();
            commitRemovals();
            commitObjects();
            commitProperties();
            target.commit();
            logger.debug("...commit completed.");
            if (logger.isDebugEnabled()) {
                try {
                    final Clip clip = AudioSystem.getClip();
                    clip.open(AudioSystem
                            .getAudioInputStream(getClass().getResource("/sounds/transaction_complete.wav")));
                    clip.addLineListener(new LineListener() {
                        public void update(LineEvent event) {
                            if (event.getType().equals(LineEvent.Type.STOP)) {
                                logger.debug("Stopping sound");
                                clip.close();
                            }
                        }
                    });
                    clip.start();
                } catch (Exception ex) {
                    logger.debug("A transaction committed but we cannot play the commit sound.", ex);
                }
            }
        } catch (Throwable t) {
            logger.warn("Rolling back due to " + t, t);
            this.rollback();
            if (t instanceof SPPersistenceException)
                throw (SPPersistenceException) t;
            if (t instanceof FriendlyRuntimeSPPersistenceException)
                throw (FriendlyRuntimeSPPersistenceException) t;
            throw new SPPersistenceException(null, t);
        } finally {
            clear();
            this.transactionCount = 0;
        }
    } else {
        transactionCount--;
    }
}