如何将 mp3 音频文件截断 30%?

How can I truncate an mp3 audio file by 30%?

我正在尝试将音频文件截断 30%,如果音频文件的长度为 4 分钟,截断后,它应该在 72 秒左右。我已经编写了下面的代码来执行此操作,但它只有 returns 一个 0 字节的文件大小。请告诉我哪里出错了?

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。这将简单地复制字节,同时保持文件的完整性,并确保在您想要的位置进行良好的干净切割。