[英]How to get the duration of a .WAV file that is not supported by the wave module in python?
I am writing a program to annotate .wav files, so I need to play them and to know their duration. 我正在编写一个程序来注释.wav文件,因此我需要播放它们并知道其持续时间。 I can use the
winsound
module to play (using SND_ASYNC
), but I can't use the wave
module to read the file, because the compression of the files I use is not supported. 我可以使用
winsound
模块来播放(使用SND_ASYNC
),但是我不能使用wave
模块来读取文件,因为不支持压缩我使用的文件。
Should I use another module to get the duration of the .WAV files, or should I use one module for both playing and getting information about the files? 我应该使用另一个模块来获取.WAV文件的持续时间,还是应该使用一个模块来播放和获取有关文件的信息? What modules should I use?
我应该使用什么模块?
Looking at the comments, this works (I made a few changes for my own readability). 查看评论,此方法有效(我为自己的可读性进行了一些更改)。 Thanks @Aya!
谢谢@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()
Using SciPy: 使用SciPy:
from scipy.io import wavfile
Fs, x = wavfile.read("file.wav")
print('Duration: ', len(x)/Fs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.