getaudio_time.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. typedef struct {
  4. char chunkId[4];
  5. uint32_t chunkSize;
  6. char format[4];
  7. char fmt[4];
  8. uint32_t fmt_size;
  9. uint16_t audio_format;
  10. uint16_t num_channels;
  11. uint32_t sample_rate;
  12. uint32_t byte_rate;
  13. uint16_t block_align;
  14. uint16_t bits_per_sample;
  15. char data[4];
  16. uint32_t data_size;
  17. } WavHeader;
  18. int main(int argc, char *argv[]) {
  19. FILE *file;
  20. WavHeader header;
  21. uint32_t subchunk2Size;
  22. uint32_t byteRate;
  23. // uint32_t sampleRate;
  24. // uint32_t numChannels;
  25. // uint32_t bitsPerSample;
  26. uint32_t dataSize;
  27. double duration;
  28. if (argc < 2) {
  29. printf("Usage: %s <filename>\n", argv[0]);
  30. return 1;
  31. }
  32. file = fopen(argv[1], "rb");
  33. if (!file) {
  34. perror("Error opening file");
  35. return 1;
  36. }
  37. // 读取WAV文件头
  38. fread(&header, sizeof(WavHeader), 1, file);
  39. // 确保是RIFF WAVE CHUNK
  40. if (header.chunkId[0] != 'R' || header.chunkId[1] != 'I' || header.chunkId[2] != 'F' || header.chunkId[3] != 'F'
  41. || header.format[0] != 'W' || header.format[1] != 'A' || header.format[2] != 'V' || header.format[3] != 'E') {
  42. // printf("Not a valid WAV file.\n");
  43. printf("0");
  44. fclose(file);
  45. return 1;
  46. }
  47. // 跳过子块大小和格式信息
  48. // fseek(file, 12, SEEK_CUR);
  49. // 读取子块大小和字节率
  50. // fread(&subchunk2Size, sizeof(uint32_t), 1, file);
  51. // fread(&byteRate, sizeof(uint32_t), 1, file);
  52. // 读取样本率和通道数
  53. // fread(&sampleRate, sizeof(uint32_t), 1, file);
  54. // fread(&numChannels, sizeof(uint32_t), 1, file);
  55. // 读取样本位深度
  56. // fread(&bitsPerSample, sizeof(uint32_t), 1, file);
  57. // 计算数据大小
  58. // dataSize = subchunk2Size;
  59. // 计算时长(秒)
  60. duration = (double)header.chunkSize / (header.bits_per_sample * header.num_channels * header.sample_rate / 8);
  61. // printf("Channels: %hu \n", header.num_channels);
  62. // printf("Sample Rate: %u \n", header.sample_rate);
  63. // printf("Byte Rate: %hu \n", header.byte_rate);
  64. // printf("Bits per Sample: %hu \n", header.bits_per_sample);
  65. // printf("Data Size: %u \n", header.data_size);
  66. // printf("Duration %.2f seconds", duration);
  67. printf("%.2f", duration);
  68. fclose(file);
  69. return 0;
  70. }