001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.io.File;
005import java.io.IOException;
006import java.net.URL;
007
008import javax.sound.sampled.AudioFormat;
009import javax.sound.sampled.AudioInputStream;
010import javax.sound.sampled.AudioSystem;
011import javax.sound.sampled.UnsupportedAudioFileException;
012
013import org.openstreetmap.josm.Main;
014
015/**
016 * Utils functions for audio.
017 *
018 * @author David Earl <david@frankieandshadow.com>
019 * @since 1462
020 */
021public final class AudioUtil {
022
023    private AudioUtil() {
024        // Hide default constructor for utils classes
025    }
026
027    /**
028     * Returns calibrated length of recording in seconds.
029     * @param wavFile the recording file (WAV format)
030     * @return the calibrated length of recording in seconds.
031     */
032    public static double getCalibratedDuration(File wavFile) {
033        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
034                new URL("file:".concat(wavFile.getAbsolutePath())))) {
035            AudioFormat audioFormat = audioInputStream.getFormat();
036            long filesize = wavFile.length();
037            double bytesPerSecond = audioFormat.getFrameRate() /* frames per second */
038                * audioFormat.getFrameSize() /* bytes per frame */;
039            double naturalLength = filesize / bytesPerSecond;
040            double calibration = Main.pref.getDouble("audio.calibration", 1.0 /* default, ratio */);
041            return naturalLength / calibration;
042        } catch (UnsupportedAudioFileException | IOException e) {
043            return 0.0;
044        }
045    }
046}