Python Library: pydub

Manipulate audio with an simple and easy high level interface.

18 Sep 2022

Library resources
PyPI https://pypi.org/project/pydub/
Homepage http://pydub.com/
Github https://github.com/jiaaro/pydub/
Documentation ---
pip3 install pydub

Snippets

open a WAV file

from pydub import AudioSegment

song = AudioSegment.from_wav("never_gonna_give_you_up.wav")

...or an mp3

song = AudioSegment.from_mp3("never_gonna_give_you_up.mp3")

... or an ogg, or flv, or anything else ffmpeg supports

ogg_version = AudioSegment.from_ogg("never_gonna_give_you_up.ogg")
flv_version = AudioSegment.from_flv("never_gonna_give_you_up.flv")
mp4_version = AudioSegment.from_file("never_gonna_give_you_up.mp4", "mp4")
wma_version = AudioSegment.from_file("never_gonna_give_you_up.wma", "wma")
aac_version = AudioSegment.from_file("never_gonna_give_you_up.aiff", "aac")

Slice audio

pydub does things in miliseconds

ten_seconds = 10 * 1000

first_10_seconds = song[:10000]

last_5_seconds = song[-5000:]

pydub does things in miliseconds

ten_seconds = 10 * 1000

first_10_seconds = song[:10000]

last_5_seconds = song[-5000:]

Need to install ffprobe for .m4a conversion.
➡️ ffmpeg

convert all mp4 and flv files in a folder to mp3

import os
import glob
from pydub import AudioSegment

video_dir = '/home/johndoe/downloaded_videos/'  # Path where the videos are located
extension_list = ('*.mp4', '*.flv')

os.chdir(video_dir)
for extension in extension_list:
    for video in glob.glob(extension):
        mp3_filename = os.path.splitext(os.path.basename(video))[0] + '.mp3'
        AudioSegment.from_file(video).export(mp3_filename, format='mp3')

How to convert m4a to wav using pydub

m4a_file = '20211210_151013.m4a'
wav_filename = r"F:\20211210_151013.wav"
from pydub import AudioSegment
track = AudioSegment.from_file(m4a_file,  format= 'm4a')
file_handle = track.export(wav_filename, format='wav')

links

social