FLAC is the go-to compression algorithm for audio if you want to maintain a perfect reconstruction of the original data. FLAC stands for Free Lossless Audio Codec. Maintained by Xiph.org, it is free and open-source, and remains the most widely supported lossless audio codec. Other audio compression techniques such as MP3 or AAC can remove perceptually redundant information in the signal.
Sonos has created pyFLAC: a Python library for realtime lossless audio compression using libFLAC.
In the spirit of open-source, we are releasing pyFLAC as a free-to-use package which can be installed directly from PyPi using pip.
pip3 install pyflac
Below is a simple example of how you might use pyFLAC alongside python-sounddevice to capture raw audio data from a microphone, and then add the compressed audio to a queue for processing in a separate thread.
import queue import pyflac import sounddevice as sd class FlacAudioStream: def __init__(self): self.stream = sd.InputStream(dtype='int16', callback=self.audio_callback) self.encoder = pyflac.StreamEncoder(callback=self.encoder_callback, sample_rate=self.stream.samplerate) self.queue = queue.SimpleQueue() def audio_callback(self, indata, frames, sd_time, status): self.encoder.process(indata) def encoder_callback(self, buffer, num_bytes, num_samples, current_frame): self.queue.put(buffer) audio = FlacAudioStream() audio.stream.start()
Read more on the Sonos blog.