Example usage for javax.sound.sampled AudioInputStream getFrameLength

List of usage examples for javax.sound.sampled AudioInputStream getFrameLength

Introduction

In this page you can find the example usage for javax.sound.sampled AudioInputStream getFrameLength.

Prototype

public long getFrameLength() 

Source Link

Document

Obtains the length of the stream, expressed in sample frames rather than bytes.

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 w  w  .  ja  v  a  2 s .  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:Main.java

public static void main(String[] argv) throws Exception {
    AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile"));
    //    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);
    }//from  w ww  . j  av  a 2s.co m

    SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, stream.getFormat(),
            ((int) stream.getFrameLength() * format.getFrameSize()));
    SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
    line.open(stream.getFormat());
    line.start();

    int numRead = 0;
    byte[] buf = new byte[line.getBufferSize()];
    while ((numRead = stream.read(buf, 0, buf.length)) >= 0) {
        int offset = 0;
        while (offset < numRead) {
            offset += line.write(buf, offset, numRead - offset);
        }
    }
    line.drain();
    line.stop();
}

From source file:org.sipfoundry.voicemail.VmMessage.java

/**
 * Combine two wav files into one bigger one
 * /*from w  ww .j  a v  a  2  s.  co  m*/
 * @param newFile
 * @param orig1
 * @param orig2
 * @throws Exception
 */
static void concatAudio(File newFile, File orig1, File orig2) throws Exception {
    String operation = "dunno";
    try {
        operation = "getting AudioInputStream from " + orig1.getPath();
        AudioInputStream clip1 = AudioSystem.getAudioInputStream(orig1);
        operation = "getting AudioInputStream from " + orig2.getPath();
        AudioInputStream clip2 = AudioSystem.getAudioInputStream(orig2);

        operation = "building SequnceInputStream";
        AudioInputStream concatStream = new AudioInputStream(new SequenceInputStream(clip1, clip2),
                clip1.getFormat(), clip1.getFrameLength() + clip2.getFrameLength());

        operation = "writing SequnceInputStream to " + newFile.getPath();
        AudioSystem.write(concatStream, AudioFileFormat.Type.WAVE, newFile);
        LOG.info("VmMessage::concatAudio created combined file " + newFile.getPath());
    } catch (Exception e) {
        String trouble = "VmMessage::concatAudio Problem while " + operation;
        //           LOG.error(trouble, e);
        throw new Exception(trouble, e);
    }
}

From source file:org.sipfoundry.voicemail.Message.java

public long getDuration() {
    // Calculate the duration (in seconds) from the Wav file
    File wavFile = getWavFile();//from   w  w  w. j  a v a 2 s  . co m
    if (wavFile != null) {
        try {
            AudioInputStream ais = AudioSystem.getAudioInputStream(wavFile);
            float secs = ais.getFrameLength() / ais.getFormat().getFrameRate();
            m_duration = Math.round(secs); // Round up.
        } catch (EOFException e) {
            m_duration = 0;
        } catch (Exception e) {
            String trouble = "Message::getDuration Problem determining duration of " + getWavFile().getPath();
            LOG.error(trouble, e);
            throw new RuntimeException(trouble, e);
        }
    }
    return m_duration;
}

From source file:org.sipfoundry.voicemail.mailbox.AbstractMailboxManager.java

protected void concatAudio(File newFile, File orig1, File orig2) throws Exception {
    String operation = "dunno";
    AudioInputStream clip1 = null;
    AudioInputStream clip2 = null;
    AudioInputStream concatStream = null;
    try {//from w  w w . java 2s .  c  o  m
        operation = "getting AudioInputStream from " + orig1.getPath();
        clip1 = AudioSystem.getAudioInputStream(orig1);
        operation = "getting AudioInputStream from " + orig2.getPath();
        clip2 = AudioSystem.getAudioInputStream(orig2);

        operation = "building SequnceInputStream";
        concatStream = new AudioInputStream(new SequenceInputStream(clip1, clip2), clip1.getFormat(),
                clip1.getFrameLength() + clip2.getFrameLength());

        operation = "writing SequnceInputStream to " + newFile.getPath();
        AudioSystem.write(concatStream, AudioFileFormat.Type.WAVE, newFile);
        LOG.info("VmMessage::concatAudio created combined file " + newFile.getPath());
    } catch (Exception e) {
        String trouble = "VmMessage::concatAudio Problem while " + operation;
        throw new Exception(trouble, e);
    } finally {
        IOUtils.closeQuietly(clip1);
        IOUtils.closeQuietly(clip2);
        IOUtils.closeQuietly(concatStream);
    }
}

From source file:tvbrowser.extras.reminderplugin.ReminderPlugin.java

/**
 * Plays a sound.//from   w ww .ja  va2  s.c om
 *
 * @param fileName
 *          The file name of the sound to play.
 * @return The sound Object.
 */
public static Object playSound(final String fileName) {
    try {
        if (StringUtils.endsWithIgnoreCase(fileName, ".mid")) {
            final Sequencer sequencer = MidiSystem.getSequencer();
            sequencer.open();

            final InputStream midiFile = new FileInputStream(fileName);
            sequencer.setSequence(MidiSystem.getSequence(midiFile));

            sequencer.start();

            new Thread("Reminder MIDI sequencer") {
                @Override
                public void run() {
                    setPriority(Thread.MIN_PRIORITY);
                    while (sequencer.isRunning()) {
                        try {
                            Thread.sleep(100);
                        } catch (Exception ee) {
                            // ignore
                        }
                    }

                    try {
                        sequencer.close();
                        midiFile.close();
                    } catch (Exception ee) {
                        // ignore
                    }
                }
            }.start();

            return sequencer;
        } else {
            final AudioInputStream ais = AudioSystem.getAudioInputStream(new File(fileName));

            final AudioFormat format = ais.getFormat();
            final DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

            if (AudioSystem.isLineSupported(info)) {
                final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

                line.open(format);
                line.start();

                new Thread("Reminder audio playing") {
                    private boolean stopped;

                    @Override
                    public void run() {
                        byte[] myData = new byte[1024 * format.getFrameSize()];
                        int numBytesToRead = myData.length;
                        int numBytesRead = 0;
                        int total = 0;
                        int totalToRead = (int) (format.getFrameSize() * ais.getFrameLength());
                        stopped = false;

                        line.addLineListener(new LineListener() {
                            public void update(LineEvent event) {
                                if (line != null && !line.isRunning()) {
                                    stopped = true;
                                    line.close();
                                    try {
                                        ais.close();
                                    } catch (Exception ee) {
                                        // ignore
                                    }
                                }
                            }
                        });

                        try {
                            while (total < totalToRead && !stopped) {
                                numBytesRead = ais.read(myData, 0, numBytesToRead);

                                if (numBytesRead == -1) {
                                    break;
                                }

                                total += numBytesRead;
                                line.write(myData, 0, numBytesRead);
                            }
                        } catch (Exception e) {
                        }

                        line.drain();
                        line.stop();
                    }
                }.start();

                return line;
            } else {
                URL url = new File(fileName).toURI().toURL();
                AudioClip clip = Applet.newAudioClip(url);
                clip.play();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        if ((new File(fileName)).isFile()) {
            URL url;
            try {
                url = new File(fileName).toURI().toURL();
                AudioClip clip = Applet.newAudioClip(url);
                clip.play();
            } catch (MalformedURLException e1) {
            }
        } else {
            String msg = mLocalizer.msg("error.1", "Error loading reminder sound file!\n({0})", fileName);
            JOptionPane.showMessageDialog(UiUtilities.getBestDialogParent(MainFrame.getInstance()), msg,
                    Localizer.getLocalization(Localizer.I18N_ERROR), JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:org.jtrfp.trcl.core.ResourceManager.java

public ResourceManager(final TR tr) {
    this.tr = tr;
    try {/*w  ww. j a v  a  2s  . c o m*/
        Class.forName("de.quippy.javamod.multimedia.mod.loader.tracker.ProTrackerMod");
        Class.forName("de.quippy.javamod.multimedia.mod.ModContainer"); // ModContainer uses the ModFactory!!
    } catch (Exception e) {
        tr.showStopper(e);
    }
    gpuResidentMODs = new CachedObjectFactory<String, GPUResidentMOD>() {
        @Override
        protected GPUResidentMOD generate(String key) {
            return new GPUResidentMOD(tr, getMOD(key));
        }//end generate(...)
    };
    soundTextures = new CachedObjectFactory<String, SoundTexture>() {
        @Override
        protected SoundTexture generate(String key) {
            try {
                final AudioInputStream ais = AudioSystem
                        .getAudioInputStream(getInputStreamFromResource("SOUND\\" + key));
                final FloatBuffer fb = ByteBuffer.allocateDirect((int) ais.getFrameLength() * 4)
                        .order(ByteOrder.nativeOrder()).asFloatBuffer();
                int value;
                while ((value = ais.read()) != -1) {
                    fb.put(((float) (value - 128)) / 128f);
                }
                fb.clear();
                return tr.soundSystem.get().newSoundTexture(fb, (int) ais.getFormat().getFrameRate());
            } catch (Exception e) {
                tr.showStopper(e);
                return null;
            }
        }
    };

    setupPODListeners();
}

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

/**
 * /* www .  ja  va  2 s .c  om*/
 * @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  ww w  . j a v a2 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:it.sardegnaricerche.voiceid.sr.VCluster.java

public void trimSegments(File inputFile) throws IOException {
    String base = Utils.getBasename(inputFile);
    File mydir = new File(base);
    mydir.mkdirs();//www .  j a  v a 2 s  . co m
    String mywav = mydir.getAbsolutePath() + "/" + this.getLabel() + ".wav";
    AudioFileFormat fileFormat = null;
    AudioInputStream inputStream = null;
    AudioInputStream shortenedStream = null;
    AudioInputStream current = null;
    int bytesPerSecond = 0;
    long framesOfAudioToCopy = 0;
    wavFile = new File(mywav);
    try {
        fileFormat = AudioSystem.getAudioFileFormat(inputFile);
        AudioFormat format = fileFormat.getFormat();
        boolean firstTime = true;

        for (VSegment s : this.getSegments()) {
            bytesPerSecond = format.getFrameSize() * (int) format.getFrameRate();
            inputStream = AudioSystem.getAudioInputStream(inputFile);
            inputStream.skip(0);
            inputStream.skip((int) (s.getStart() * 100) * bytesPerSecond / 100);
            framesOfAudioToCopy = (int) (s.getDuration() * 100) * (int) format.getFrameRate() / 100;

            if (firstTime) {
                shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
            } else {
                current = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
                shortenedStream = new AudioInputStream(new SequenceInputStream(shortenedStream, current),
                        format, shortenedStream.getFrameLength() + framesOfAudioToCopy);
            }
            firstTime = false;
        }
        AudioSystem.write(shortenedStream, fileFormat.getType(), wavFile);
    } catch (Exception e) {
        logger.severe(e.getMessage());
        e.printStackTrace();
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
        if (shortenedStream != null)
            try {
                shortenedStream.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
        if (current != null)
            try {
                current.close();
            } catch (Exception e) {
                logger.severe(e.getMessage());
            }
    }
    logger.fine("filename: " + wavFile.getAbsolutePath());
}