代码之家  ›  专栏  ›  技术社区  ›  Student

如何在Java中获取声音文件的总时间?

  •  15
  • Student  · 技术社区  · 16 年前

    如何在Java中获取声音文件的总时间?

    --更新

    long audioFileLength=audioFile.length();

        recordedTimeInSec = audioFileLength / (frameSize * frameRate);
    

    --更新

    另一个工作代码(使用@mdma的提示):

        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
        AudioFormat format = audioInputStream.getFormat();
        long audioFileLength = file.length();
        int frameSize = format.getFrameSize();
        float frameRate = format.getFrameRate();
        float durationInSeconds = (audioFileLength / (frameSize * frameRate));
    
    2 回复  |  直到 16 年前
        1
  •  30
  •   mdma    16 年前

    给予 File

    File file = ...;
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
    AudioFormat format = audioInputStream.getFormat();
    long frames = audioInputStream.getFrameLength();
    double durationInSeconds = (frames+0.0) / format.getFrameRate();  
    
        2
  •  -1
  •   Milo Banks    8 年前

    这是一个简单的方法:

    FileInputStream fileInputStream = null;
    long duration = 0;
    
    try {
        fileInputStream = new FileInputStream(pathToFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    
    try {
        duration = Objects.requireNonNull(fileInputStream).getChannel().size() / 128;
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(duration)