Calculate how long it will take to play the given number of bytes of Audio. - Java javax.sound.sampled

Java examples for javax.sound.sampled:Audio

Description

Calculate how long it will take to play the given number of bytes of Audio.

Demo Code

/*/*from w w w.j a  v  a 2s. c  o m*/
 This file is part of the Greenfoot program. 
 Copyright (C) 2005-2009,2011  Poul Henriksen and Michael Kolling 
         
 This program is free software; you can redistribute it and/or 
 modify it under the terms of the GNU General Public License 
 as published by the Free Software Foundation; either version 2 
 of the License, or (at your option) any later version. 
         
 This program is distributed in the hope that it will be useful, 
 but WITHOUT ANY WARRANTY; without even the implied warranty of 
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 GNU General Public License for more details. 
         
 You should have received a copy of the GNU General Public License 
 along with this program; if not, write to the Free Software 
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. 
         
 This file is subject to the Classpath exception as provided in the  
 LICENSE.txt file that accompanied this code.
 */
//package com.java2s;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;

public class Main {
    /**
     * Calculate how long it will take to play the given number of bytes.
     * 
     * @param bytes Number of bytes.
     * @param format The format used to play the bytes.
     * @return time in ms or -1 if it could not be calculated.
     */
    public static long getTimeToPlayBytes(long bytes, AudioFormat format) {
        return getTimeToPlayFrames(bytes / format.getFrameSize(), format);
    }

    /**
     * Calculate how long it will take to play the given number of frames.
     * 
     * @param bytes Number of bytes.
     * @param format The format used to play the bytes.
     * @return time in ms or -1 if it could not be calculated.
     */
    public static long getTimeToPlayFrames(long frames, AudioFormat format) {
        if (format.getFrameRate() != AudioSystem.NOT_SPECIFIED) {
            return (long) (1000 * frames / format.getFrameRate());
        } else {
            return -1;
        }
    }
}

Related Tutorials