Manipulating Raw Audio Data with Python’s Deprecated Module ‘audioop’

To start, let’s make sure you have this bad boy installed on your machine. If not, head over to your terminal or command prompt and type:
pip install audioop
()

Now that we’ve got the basics out of the way, what ‘audioop’ actually does. It provides support for some useful operations on sound fragments consisting of signed integer samples 8, 16, 24 or 32 bits wide, stored in bytes-like objects.

Here’s an example to get you started:

# Import the necessary modules
import audioop # Module for audio operations
from array import array # Module for creating arrays

# Load a WAV file into memory
with open('example_audio.wav', 'rb') as f: # Open the WAV file in read-only mode
    data = bytearray(f.read()) # Read the file and store the data in a bytearray object

# Convert the bytes-like object to an array of signed 16-bit integers
snd = array('h', [ord(x) - 128 for x in data[20:]]) # Convert the data to an array of signed 16-bit integers by subtracting 128 from each byte

# Apply a gain (amplitude increase or decrease) to the audio signal
gain = 2.5 # Set the gain value to 2.5
new_data = bytearray() # Create a new bytearray to store the modified audio data
for i, sample in enumerate(snd): # Loop through each sample in the array
    new_sample = int((sample * gain) // 16) # Multiply the sample by the gain and divide by 16 to increase the amplitude
    if new_sample > 255: # Check if the new sample value is greater than 255
        raise ValueError('Gain too high') # If so, raise an error to prevent overflowing the output data
    new_data.append(new_sample & 0xFF) # Convert the new sample to an unsigned byte and append it to the new data array

# Write the modified audio signal back to a file
with open('modified_audio.wav', 'wb') as f: # Open a new file in write-only mode
    f.write(b'RIFF' + b'\x00\x00\x00\x01' + snd[0:4] + array('B', [8, 0, 0, 1]).tostring() + new_data) # Write the modified audio data to the file in WAV format

In this example, we first load a WAV file into memory and convert the bytes-like object to an array of signed 16-bit integers. We then apply a gain (amplitude increase or decrease) by multiplying each sample with a factor and converting it back to unsigned byte for writing to a new WAV file.

Note that we’re using ‘array’ instead of ‘list’ here because ‘audioop’ requires an array-like object as input. Also, be careful not to apply too high gain or you might overflow the output data and cause errors.

A brief introduction to manipulating raw audio data with Python’s deprecated module ‘audioop’. While this package is no longer actively maintained, it still has some useful functions for certain use cases (such as working with legacy code or specific file formats). Just be aware that its usage might become more limited in future versions of Python.

SICORPS