简体   繁体   中英

How to determine theoretical filesize of converted audio file without actually converting (i.e. mp3 to wav)

Background: I am writing a python script that will take in an audio file and modify it using pydub. Pydub seems to require converting audio input to a wav format though, which has a 4GB limit. So I put in a 400MB.m4a file into pydub and get an error that the file is too large.

Instead of having pydub run for a couple minutes, then throw an error if the converted decompressed size is too large, I would like to quickly calculate ahead of time what the decompressed filesize would be. If over 4GB, my script will chop the original audio and then run through pydub.

Thanks.

It's simple arithmetic to calculate the size of a theoretical.WAV file. The size, in bytes, is the bit depth divided by 8, multiplied by the sample rate, multiplied by the duration, multiplied by the number of channels.

So if you had an audio clip that was 3:20 long, 44100Hz, 16-bit and stereo, the calculation would be:

sample_rate = 44100 # Hz/Samples per second - CD Quality
bit_depth = 16 # 2 bytes; CD quality
channels = 2 # stereo
duration = 200.0 # seconds

file_size = sample_rate * (bit_depth / 8) * channels * duration
        # = 44100 * (2) * 2 * 200
        # = 35280000 bytes
        # = 35.28 MB (megabytes)

I found this online audio file size calculator which you can also use to confirm your math: https://www.colincrawley.com/audio-file-size-calculator/

If instead you wanted to figure out the other direction, ie the size of a theoretical compressed file, it depends on how you're doing the compression. Typical compression, thankfully, uses just a fixed bitrate, meaning the math to figure out the resulting compressed file size is really simple.

So, if you had a 3:20 audio clip you wanted to convert to MP3, at a bitrate of 128kbps (kilobits per second, 128 is a common mid-range quality setting), the calculation would just be the bit rate, divided by 8 (bits per byte) multiplied by the duration:

bits_per_kb = 1000
bitrate_kbps = 128
bits_per_byte = 8
duration_seconds = 200
filesize_bytes = (bitrate_kbps * bits_per_kb / bits_per_byte) * duration_seconds
             # = (128000 / 8) * 200
             # = (16) * 200
             # = 3200000 bytes
             # = 3.2 MB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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