如何确定 wav 文件的持续时间 [英] How can i determine duration of wav file

查看:57
本文介绍了如何确定 wav 文件的持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 .wav 文件,我需要以秒为单位获取它们的持续时间.到目前为止,我一直在确定它:

I'm working with .wav files and I need to get their duration in seconds. So far I've been determining it with:

文件大小/byte_rate

Byte_rate 为 (Sample Rate * BitsPerSample * Channels)/8.它适用于较小的文件,当我尝试解析较大的文件时,我得到的秒数比实际持续时间长.

Byte_rate being (Sample Rate * BitsPerSample * Channels) / 8. And it works, with smaller files, when I try to parse bigger files, I get more seconds than the actual duration.

示例:

大小(字节):45207622 Byte_rate:176400 持续时间:256(45207622/176400)

Size(bytes): 45207622 Byte_rate: 176400 Duration: 256 (45207622 / 176400)

但实际持续时间是250...

but the actual duration is 250...

仅供参考:我已经仔细检查了大小和 byte_rate,它们是正确的.

FYI: I've double checked the size and byte_rate, they are correct.

推荐答案

如果没有示例 RIFF 标头或您的代码,将很难回答您问题中的具体细节.(即为什么你的数学没有达到你的预期结果.)

Without a sample RIFF header or your code, it would be difficult to answer the specifics in your question. (i.e. Why your math isn't coming to your expected result.)

但是,既然您已在注释中指定您使用 C 语言工作,我是否建议使用 sox 库而不是使用新编写的代码解析标头?除了捕获相当数量的边缘情况外,这还允许您支持任何格式 sox 支持阅读,而无需自己编写任何阅读代码.(尽管任何倾向于这样做的人都应该看看 有人可以解释一下.wav(WAVE) 文件头?RIFFWAVE 格式规范.该过程应该大致是问题中描述的方法,至少在大多数情况下是这样.)

However, since you've specified that you're working in C in the comments, might I suggest using the sox library instead of parsing the headers with newly written code? In addition to catching a fair number of edge cases, this allows you to support any format sox supports reading without having to write any of the reading code yourself. (Though anyone inclined to do so should probably take a look at Can someone explain .wav(WAVE) file headers? and RIFF WAVE format specifications. The process should be roughly the method described in the question, at least in most cases. )

示例代码:

#include <sox.h>
#include <stdio.h>

int main(int argc, char **argv) {
  sox_format_t *fmt;
  if(argc < 2) {
    printf("Please provide audio file.\n");
    return 1;
  }
  fmt = sox_open_read(argv[1], NULL, NULL, NULL);
  __uint64_t ws = fmt->signal.length / fmt->signal.channels;
  if(fmt->signal.length) {
    printf("%0.2f seconds long\n", (double)ws / fmt->signal.rate);
  } else {
    printf("Cannot determine duration from header.\n");
  }
}

对于任何好奇的人,我主要是从 sox 命令行工具的源代码中获得的.

For anyone curious, I largely derived this from the sox command line tool's source code.

这篇关于如何确定 wav 文件的持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆