简体   繁体   English

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

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

I am trying to truncate an audio file by 30%, if the audio file was 4 minutes long, after truncating it, it should be around 72 seconds. 我正在尝试将音频文件截断30%,如果音频文件的长度为4分钟,则在将其截断后应为72秒左右。 I have written the code below to do it but it only returns a 0 byte file size. 我已经写了下面的代码来做到这一点,但它只返回0字节的文件大小。 Please tell me where i went wrong? 请告诉我我哪里出问题了?

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()

You are trying to read your file a second time which will result in no data, eg len(in_file.read() . Instead read the whole file into a variable and then calculate the length of that. The variable can then be used a second time. 您正在尝试第二次读取文件,这将导致没有数据,例如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])

Also it is better to multiply first and then divide to avoid having to work with floating point numbers. 另外,最好先相乘然后相除,以避免必须使用浮点数。

You cannot reliably truncate an MP3 file by byte size and expect it to be equivalently truncated in audio time length. 您不能按字节大小可靠地截断MP3文件,并期望它在音频时间长度上被等效地截断。

MP3 frames can change bitrate. MP3帧可以更改比特率。 While your method will sort of work, it won't be all that accurate. 尽管您的方法可以完成工作,但并不会那么准确。 Additionally, you'll undoubtedly break frames leaving glitches at the end of the file. 另外,您无疑会破坏帧,在文件末尾留下毛刺。 You will also lose ID3v1 tags (if you still use them... better to use ID3v2 anyway). 您还将丢失ID3v1标签(如果仍然使用它们,则最好还是使用ID3v2)。

Consider executing FFmpeg with -acodec copy instead. 考虑使用-acodec copy执行FFmpeg。 This will simply copy the bytes over while maintaining the integrity of the file, and ensuring a good clean cut where you want it to be. 这将简单地复制字节,同时保持文件的完整性,并确保将文件保留在想要的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM