【问题标题】:How to get the duration of a .WAV file that is not supported by the wave module in python?如何获取python中wave模块不支持的.WAV文件的持续时间?
【发布时间】:2013-06-22 08:17:02
【问题描述】:

我正在编写一个程序来注释 .wav 文件,所以我需要播放它们并知道它们的持续时间。我可以使用winsound模块播放(使用SND_ASYNC),但是我不能使用wave模块读取文件,因为我使用的文件不支持压缩。

我应该使用另一个模块来获取 .WAV 文件的持续时间,还是应该使用一个模块来播放和获取有关文件的信息?我应该使用哪些模块?

【问题讨论】:

  • 先解压然后让Python支持怎么样?
  • 我不知道该怎么做。我们在这里谈论 5000 个文件。
  • this 工作吗?
  • 这看起来很有希望。但是我在尝试这个时在a=f.read(4) 得到了一个UnicodeDecodeError(在为支持的文件执行此操作时也是如此)。我应该以不同的方式阅读f吗?
  • @Lewistrick 您可能需要以二进制模式打开文件。将第 3 行更改为 f=open(path,"rb")

标签: python duration wave


【解决方案1】:

看看 cmets,这是可行的(我为自己的可读性做了一些更改)。谢谢@Aya!

import os
path="c:\\windows\\system32\\loopymusic.wav"
f=open(path,"rb")

# read the ByteRate field from file (see the Microsoft RIFF WAVE file format)
# https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
# ByteRate is located at the first 28th byte
f.seek(28)
a = f.read(4)

# convert string a into integer/longint value
# a is little endian, so proper conversion is required
byteRate = 0
for i in range(4):
    byteRate += a[i] * pow(256, i)

# get the file size in bytes
fileSize = os.path.getsize(path)  

# the duration of the data, in milliseconds, is given by
ms = ((fileSize - 44) * 1000)) / byteRate

print "File duration in miliseconds : " % ms
print "File duration in H,M,S,mS : " % ms / (3600 * 1000) % "," % ms / (60 * 1000) % "," % ms / 1000 % "," ms % 1000
print "Actual sound data (in bytes) : " % fileSize - 44
f.close()

【讨论】:

    【解决方案2】:

    使用 SciPy:

     from scipy.io import wavfile
     Fs, x = wavfile.read("file.wav")
     print('Duration: ', len(x)/Fs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多