Python 如何将mp3音频文件截断30%?
我正在尝试将一个音频文件截断30%,如果该音频文件的长度为4分钟,则截断后的长度应为72秒左右。我已经编写了下面的代码来执行此操作,但它只返回0字节的文件大小。请告诉我哪里出错了Python 如何将mp3音频文件截断30%?,python,audio,mp3,Python,Audio,Mp3,我正在尝试将一个音频文件截断30%,如果该音频文件的长度为4分钟,则截断后的长度应为72秒左右。我已经编写了下面的代码来执行此操作,但它只返回0字节的文件大小。请告诉我哪里出错了 def loadFile(): with open('music.mp3', 'rb') as in_file: data = len(in_file.read()) with open('output.mp3', 'wb') as out_file: n
def loadFile():
with open('music.mp3', 'rb') as in_file:
data = len(in_file.read())
with open('output.mp3', 'wb') as out_file:
ndata = newBytes(data)
out_file.write(in_file.read()[:ndata])
def newBytes(bytes):
newLength = (bytes/100) * 30
return int(newLength)
loadFile()
您正在尝试第二次读取文件,这将导致没有数据,例如
len(in_file.read()
。而是将整个文件读入一个变量,然后计算该变量的长度。然后可以再次使用该变量
def newBytes(bytes):
return (bytes * 70) / 100
def loadFile():
with open('music.mp3', 'rb') as in_file:
data = in_file.read()
with open('output.mp3', 'wb') as out_file:
ndata = newBytes(len(data))
out_file.write(data[:ndata])
此外,最好先乘后除,以避免使用浮点数。您无法可靠地按字节大小截断MP3文件,并期望它在音频时间长度上被等效截断 MP3帧可以更改比特率。虽然您的方法会起作用,但不会那么精确。此外,毫无疑问,您会打断帧,在文件末尾留下小故障。您还将丢失ID3v1标记(如果您仍然使用它们…最好还是使用ID3v2)
请考虑使用
-acodec copy
执行FFmpeg。这将在保持文件完整性的同时简单地复制字节,并确保在您希望的位置进行良好的剪切。非常感谢。