We come across files almost every day in our tech journey. Sometimes, we have to use Python as our programming language to perform various operations on these files. One such operation is obtaining the size of each sample in our AIFF-C files in bytes.
File types range from your regular .doc and .xls files to the not-so-common AIFF files. AIFF stands for Audio Interchange File Format, a standard file format used to store audio files for our
Frame: one sample of the audio data per channel.
Frame rate: the number of times per unit time the sound data is sampled.
Number of channels: indicates if the audio is mono, stereo, or quadro.
The sample size: the size of each sample in bytes.
From these parameters, you can see that a frame is made up of channels that each contain sample bytes of file data.
To get the sample size of your aifc file in your Python code, you will need to call on the getsampwidth()
function. This function is part of the Python aifc module that provides support for reading and writing AIFF and AIFF-C files. The aifc module contains other functions that you can use to work with your AIFF files in your code.
Calling this function on your file involves the following steps:
import
statement into your working file.aifc.open()
function, and set the mode to read mode.getsampwidth()
function on the object.aifc.close()
function to prevent file leak.print()
function or, pass the result into a variable that can be further used in your code.The function returns the file byte size as an integer, which can then be further manipulated like any other Python integer type value. The code for this process is shown below:
>>> import aifc
>>> import audio_file
>>> audio_obj = aifc.open('audio_file','r')
>>> byte_size = audio_obj.aifcgetsampwidth()
>>> aifc.close()
>>> print(byte_size)
## the file byte size is printed on the console.
You can also carry out this operation with a context manager. A context manager helps you manage your with
statement, as using it in our code makes our code more concise.
The code below shows how we can perform the same operation using a context manager:
>>> import aifc
>>> import audio_file
>>> with aifc.open('audio_file', 'r') as audio_obj:
byte_size = audio_obj.getsampwidth()
>>> print(byte_size)
## the file byte size is printed on the console.