Simple Audio Converter¶
How to build a simple audio converter in Python.
Audio Input¶
As audio input we use the kahvi011_kennybeltrey-hydrate.mp3 file from the Internet Archive. The original audio format is MPEG Audio Layer 3, 44.1 KHz, Joint Stereo, 136 Kbps, Variable Bit Rate
Code¶
The following code snippet will take any audio format supported by AVBlocks and will convert it to AAC audio in an ADTS container (*.AAC).
import sys
from avblocks import Library, MediaInfo, MediaSocket, Preset, Transcoder
def main():
Library.initialize()
with MediaInfo() as input_info:
input_info.inputs[0].file = "kahvi011_kennybeltrey-hydrate.mp3"
if input_info.open():
input_socket = MediaSocket.from_media_info(input_info)
output_socket = MediaSocket.from_preset(Preset.Audio.Generic.AAC)
output_socket.file = "kahvi011_kennybeltrey-hydrate.aac"
with Transcoder() as transcoder:
# Allow demo mode when using the demo version of the library
transcoder.allow_demo_mode = True
transcoder.inputs.add(input_socket)
transcoder.outputs.add(output_socket)
if transcoder.open():
transcoder.run()
transcoder.close()
Library.shutdown()
return 0
if __name__ == '__main__':
sys.exit(main())
How to run¶
Follow the steps in Developing with Visual Studio Code to create a Python project and add AVBlocks, but in simple_converter.py use the code from this article.
Download the kahvi011_kennybeltrey-hydrate.mp3 song from the Internet Archive and save it in the project directory.
Run the application with uv run python simple_converter.py. Wait a few seconds for the Transcoder to finish. The converted file kahvi011_kennybeltrey-hydrate.aac will be in the project directory.