Reading AAC Encoded Audio in Python
Using the freely available Python Audio Tools decoding an audio stream is pretty simple. Their site doesn’t have a solid example of using the APIs available, so I’ve written a short demonstration to decode a AAC-encoded audio file. The file I’m decoding was generated using the voice recording application on an iPod touch, although this should work for almost any audio file supported by Python Audio Tools.
import audiotools as at
print 'Opening input data auio stream... decoding'
#Create a AudioFile object out of an input file
aF = at.open('inputData.m4a')
pcmAf = aF.to_pcm()
# We'll store the data in a list, although this algorithm is suitable for
# passing the data to a second stage for online processing.
rawData = []
while True:
# This file is setup with 2 audio channels, sampled at 44.1kHz
# we'll read 256 bytes of raw data at a time,
# or 256 / 2 channels / 2 bytes per sample = 64 frames
# Since our data is only mono, we discard one of the channels.
frame = pcmAf.read(256)
for i in range(0, frame.frames):
byteArray = frame.channel(0).frame(i).to_bytes(True, True)
pcmVal = struct.unpack('h', byteArray)
rawData.append(pcmVal)
if frame.frames < 64:
# Smaller frame numbers indicate the end of file has
# been reached.
print 'End of file found. Breaking.'
break
Make sure you’ve installed Python Audio Tools first, it’s freely available from the project page. So far I’ve only had success using these libraries in Linux, Mac OS support seems doable but would take some effort to properly do.