### Install dependencies on Linux Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Install libav or ffmpeg using aptitude. ```bash # libav apt-get install libav-tools libavcodec-extra #### OR ##### # ffmpeg apt-get install ffmpeg libavcodec-extra ``` -------------------------------- ### Install dependencies on macOS Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Install libav or ffmpeg using Homebrew. ```bash # libav brew install libav #### OR ##### # ffmpeg brew install ffmpeg ``` -------------------------------- ### Install Pydub from GitHub Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Install the latest development version directly from the repository. ```bash pip install git+https://github.com/jiaaro/pydub.git@master ``` -------------------------------- ### Install Pydub via pip Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Standard installation command for the Pydub library. ```bash pip install pydub ``` -------------------------------- ### Detect and Remove DC Offset in Audio Source: https://context7.com/jiaaro/pydub/llms.txt Demonstrates how to detect and remove DC offset from audio files using pydub. You can get the offset for specific channels or remove it from all channels automatically or with a specified offset value. ```python from pydub import AudioSegment sound = AudioSegment.from_file("audio.wav") left_offset = sound.get_dc_offset(channel=1) print(f"Left channel DC offset: {left_offset}") right_offset = sound.get_dc_offset(channel=2) print(f"Right channel DC offset: {right_offset}") cleaned = sound.remove_dc_offset() left_cleaned = sound.remove_dc_offset(channel=1) right_cleaned = sound.remove_dc_offset(channel=2) corrected = sound.remove_dc_offset(offset=-0.05) ``` -------------------------------- ### Load Audio Files with AudioSegment.from_file() Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Shows how to load audio files into AudioSegment objects using various formats, including native support for WAV and RAW, and ffmpeg-based support for others like MP3. It also demonstrates loading from file handles and objects supporting the os.PathLike protocol. ```python from pydub import AudioSegment # wave and raw don’t use ffmpeg wav_audio = AudioSegment.from_file("/path/to/sound.wav", format="wav") raw_audio = AudioSegment.from_file("/path/to/sound.raw", format="raw", frame_rate=44100, channels=2, sample_width=2) # all other formats use ffmpeg mp3_audio = AudioSegment.from_file("/path/to/sound.mp3", format="mp3") # use a file you've already opened (advanced …ish) with open("/path/to/sound.wav", "rb") as wav_file: audio_segment = AudioSegment.from_file(wav_file, format="wav") # also supports the os.PathLike protocol for python >= 3.6 from pathlib import Path wav_path = Path("path/to/sound.wav") wav_audio = AudioSegment.from_file(wav_path) ``` -------------------------------- ### General Fade Effect on Audio Segment Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Apply a general fade effect to an AudioSegment, specifying start position, end position, or duration. Fades can adjust volume from a starting gain to an ending gain. ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") fade_louder_for_3_seconds_in_middle = sound1.fade(to_gain=+6.0, start=7500, duration=3000) fade_quieter_beteen_2_and_3_seconds = sound1.fade(to_gain=-3.5, start=2000, end=3000) # easy way is to use the .fade_in() convenience method. note: -120dB is basically silent. fade_in_the_hard_way = sound1.fade(from_gain=-120.0, start=0, duration=5000) fade_out_the_hard_way = sound1.fade(to_gain=-120.0, end=0, duration=5000) ``` -------------------------------- ### AudioSegment Properties Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Accessing properties of an AudioSegment object to get information about the audio data. ```APIDOC ## AudioSegment Properties ### frame_width Number of bytes for each "frame". A frame contains a sample for each channel (so for stereo you have 2 samples per frame, which are played simultaneously). `frame_width` is equal to `channels * sample_width`. For CD Audio it'll be `4` (2 channels times 2 bytes per sample). ### rms A measure of loudness. Used to compute dBFS, which is what you should use in most cases. Loudness is logarithmic (rms is not), which makes dB a much more natural scale. ### max The highest amplitude of any sample in the `AudioSegment`. Useful for things like normalization (which is provided in `pydub.effects.normalize`). ### max_dBFS The highest amplitude of any sample in the `AudioSegment`, in dBFS (relative to the highest possible amplitude value). Useful for things like normalization (which is provided in `pydub.effects.normalize`). ### duration_seconds Returns the duration of the `AudioSegment` in seconds (`len(sound)` returns milliseconds). This is provided for convenience; it calls `len()` internally. ### raw_data The raw audio data of the AudioSegment. Useful for interacting with other audio libraries or weird APIs that want audio data in the form of a bytestring. Also comes in handy if you’re implementing effects or other direct signal processing. You probably don’t need this, but if you do… you’ll know. ``` -------------------------------- ### Apply Fade In and Fade Out Source: https://context7.com/jiaaro/pydub/llms.txt Create smooth volume transitions using fade_in, fade_out, or the general fade method. ```python from pydub import AudioSegment sound = AudioSegment.from_file("audio.mp3") # Simple fade in (2 seconds) and fade out (3 seconds) faded = sound.fade_in(2000).fade_out(3000) # Using the general fade method for more control # Fade from -20dB to 0dB over first 5 seconds fade_in_custom = sound.fade(from_gain=-20.0, start=0, duration=5000) # Fade from 0dB to -10dB between 10s and 15s mid_fade = sound.fade(to_gain=-10.0, start=10000, end=15000) # Duck audio volume during a specific section ducked = sound.fade(to_gain=-8.0, start=5000, duration=2000) # Create intro with fade-in effect intro = AudioSegment.silent(duration=1000) # 1s silence intro += sound[:10000].fade_in(500) # Create outro with fade-out outro = sound[-10000:].fade_out(3000) outro += AudioSegment.silent(duration=1000) # 1s silence ``` -------------------------------- ### Create and Manipulate AudioSegment Objects Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Demonstrates creating AudioSegment objects from files and performing basic manipulations like volume adjustment, concatenation, repetition, slicing, and advanced construction from raw audio data. Operations that combine AudioSegment objects automatically handle differing audio properties by up-sampling to the higher quality. ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("/path/to/sound.wav", format="wav") sound2 = AudioSegment.from_file("/path/to/another_sound.wav", format="wav") # sound1 6 dB louder, then 3.5 dB quieter louder = sound1 + 6 quieter = sound1 - 3.5 # sound1, with sound2 appended combined = sound1 + sound2 # sound1 repeated 3 times repeated = sound1 * 3 # duration duration_in_milliseconds = len(sound1) # first 5 seconds of sound1 beginning = sound1[:5000] # last 5 seconds of sound1 end = sound1[-5000:] # split sound1 in 5-second slices _slices = sound1[::5000] # Advanced usage, if you have raw audio data: sound = AudioSegment( # raw audio data (bytes) data=b'…', # 2 byte (16 bit) samples sample_width=2, # 44.1 kHz frame rate frame_rate=44100, # stereo channels=2 ) ``` -------------------------------- ### silence.detect_nonsilent() Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Returns a list of all non-silent sections [start, end] in milliseconds of an audio segment. ```APIDOC ## silence.detect_nonsilent() ### Description Returns a list of all non-silent sections [start, end] in milliseconds of audio_segment. This is the inverse of detect_silence(). ### Parameters #### Query Parameters - **min_silence_len** (int) - Optional - The minimum length for silent sections in milliseconds. Default: 1000. - **silence_thresh** (int) - Optional - The upper bound for how quiet is silent in dBFS. Default: -16. - **seek_step** (int) - Optional - Size of the step for checking for silence in milliseconds. Default: 1. ``` -------------------------------- ### AudioSegment Fade Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Apply a fade effect to an AudioSegment, allowing control over start, end, duration, and gain levels. ```APIDOC ## AudioSegment(...).fade(to_gain=0, from_gain=0, start=None, end=None, duration=None) ### Description A general method to apply fade effects to an `AudioSegment`. You can specify fade-in, fade-out, or a fade between specific gain levels over a defined period. ### Method `fade` ### Parameters #### Keyword Arguments - **to_gain** (float) - Optional. The resulting gain change (in dB) at the end of the fade. Defaults to 0 (no change). - **from_gain** (float) - Optional. The gain change (in dB) at the beginning of the fade. Defaults to 0 (no change). - **start** (int) - Optional. The position in milliseconds where the fade effect begins. If `duration` is provided, this is the start time of the fade. - **end** (int) - Optional. The position in milliseconds where the fade effect ends. If `duration` is provided, this is the end time of the fade. - **duration** (int) - Optional. The length of the fade effect in milliseconds. Can be used with either `start` or `end`. ### Request Example ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") # Fade louder by 6 dB over 3 seconds, starting after 7.5 seconds fade_louder_effect = sound1.fade(to_gain=+6.0, start=7500, duration=3000) # Fade quieter by 3.5 dB between 2 and 3 seconds fade_quieter_effect = sound1.fade(to_gain=-3.5, start=2000, end=3000) # Fade in from silence over 5 seconds (from -120dB to 0dB) fade_in_effect = sound1.fade(from_gain=-120.0, start=0, duration=5000) # Fade out to silence over 5 seconds (from 0dB to -120dB) fade_out_effect = sound1.fade(to_gain=-120.0, end=0, duration=5000) ``` ### Response Returns a new `AudioSegment` with the fade effect applied. ### Response Example ```python # fade_louder_effect, fade_quieter_effect, fade_in_effect, fade_out_effect are new AudioSegment objects ``` ``` -------------------------------- ### Convert AudioSegment to and from numpy arrays Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Demonstrates converting audio samples to float32 numpy arrays for processing and back to an AudioSegment via scipy. ```python import numpy as np from pydub import AudioSegment sound = AudioSegment.from_file("sound1.wav") sound = sound.set_frame_rate(16000) channel_sounds = sound.split_to_mono() samples = [s.get_array_of_samples() for s in channel_sounds] fp_arr = np.array(samples).T.astype(np.float32) fp_arr /= np.iinfo(samples[0].typecode).max ``` ```python import io import scipy.io.wavfile wav_io = io.BytesIO() scipy.io.wavfile.write(wav_io, 16000, fp_arr) wav_io.seek(0) sound = pydub.AudioSegment.from_wav(wav_io) ``` -------------------------------- ### Play audio with Pydub Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Load a WAV file and play it using the Pydub playback module. ```python from pydub import AudioSegment from pydub.playback import play sound = AudioSegment.from_file("mysound.wav", format="wav") play(sound) ``` -------------------------------- ### AudioSegment Set Sample Width Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Create an equivalent AudioSegment with a specified sample width. ```APIDOC ## AudioSegment(...).set_sample_width(width) ### Description Creates an equivalent version of this `AudioSegment` with the specified sample width (in bytes). Increasing this value does not generally cause a reduction in quality. Reducing it *definitely* causes a loss in quality. Higher sample width means more dynamic range. ### Method `set_sample_width` ### Parameters #### Arguments - **width** (int) - The desired sample width in bytes (e.g., 1 for 8-bit, 2 for 16-bit). ### Request Example ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") # Convert sound1 to 16-bit audio (2 bytes per sample) sound_16bit = sound1.set_sample_width(2) ``` ### Response Returns a new `AudioSegment` with the specified sample width. ### Response Example ```python # sound_16bit is a new AudioSegment object ``` ``` -------------------------------- ### Create and export a playlist Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Combine multiple MP3 files into a single playlist with crossfades and fade-out effects. ```python from glob import glob from pydub import AudioSegment playlist_songs = [AudioSegment.from_mp3(mp3_file) for mp3_file in glob("*.mp3")] first_song = playlist_songs.pop(0) # let's just include the first 30 seconds of the first song (slicing # is done by milliseconds) beginning_of_song = first_song[:30*1000] playlist = beginning_of_song for song in playlist_songs: # We don't want an abrupt stop at the end, so let's do a 10 second crossfades playlist = playlist.append(song, crossfade=(10 * 1000)) # let's fade out the end of the last song playlist = playlist.fade_out(30) # hmm I wonder how long it is... ( len(audio_segment) returns milliseconds ) playlist_length = len(playlist) / (1000*60) # lets save it! with open("%s_minute_playlist.mp3" % playlist_length, 'wb') as out_f: playlist.export(out_f, format='mp3') ``` -------------------------------- ### Export Ogg with specific codec Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Demonstrates that exporting to Ogg defaults to the Vorbis codec. ```python from pydub import AudioSegment song = AudioSegment.from_mp3("test/data/test1.mp3") song.export("out.ogg", format="ogg") # Is the same as: song.export("out.ogg", format="ogg", codec="libvorbis") ``` -------------------------------- ### Load Audio Files Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Load audio files using specific format methods or the generic from_file method. ```python from pydub import AudioSegment song = AudioSegment.from_wav("never_gonna_give_you_up.wav") ``` ```python song = AudioSegment.from_mp3("never_gonna_give_you_up.mp3") ``` ```python 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") ``` -------------------------------- ### Load Audio Files with AudioSegment.from_file Source: https://context7.com/jiaaro/pydub/llms.txt Use `AudioSegment.from_file` to load audio from various formats. FFmpeg is required for formats other than WAV and raw PCM. You can specify format, load raw audio with parameters, load portions of files, or use file handles. ```python from pydub import AudioSegment # Load from various formats wav_audio = AudioSegment.from_file("song.wav", format="wav") mp3_audio = AudioSegment.from_file("song.mp3", format="mp3") ogg_audio = AudioSegment.from_file("song.ogg", format="ogg") # Auto-detect format from file extension audio = AudioSegment.from_file("song.mp3") # Load raw PCM audio (requires explicit parameters) raw_audio = AudioSegment.from_file( "audio.raw", format="raw", frame_rate=44100, channels=2, sample_width=2 # 16-bit audio ) # Load only a portion of the file (efficient for large files) clip = AudioSegment.from_file("song.mp3", start_second=30, duration=10) # Load from file handle with open("song.wav", "rb") as f: audio = AudioSegment.from_file(f, format="wav") # Convenience methods for common formats mp3 = AudioSegment.from_mp3("song.mp3") wav = AudioSegment.from_wav("song.wav") ogg = AudioSegment.from_ogg("song.ogg") flv = AudioSegment.from_flv("video.flv") ``` -------------------------------- ### Manipulate raw audio samples Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Accesses raw audio data as an array for custom processing. Use _spawn to create a new AudioSegment from modified samples. ```python from pydub import AudioSegment sound = AudioSegment.from_file(“sound1.wav”) samples = sound.get_array_of_samples() # then modify samples... new_sound = sound._spawn(samples) ``` ```python import array import numpy as np from pydub import AudioSegment sound = AudioSegment.from_file(“sound1.wav”) samples = sound.get_array_of_samples() # Example operation on audio data shifted_samples = np.right_shift(samples, 1) # now you have to convert back to an array.array shifted_samples_array = array.array(sound.array_type, shifted_samples) new_sound = sound._spawn(shifted_samples_array) ``` -------------------------------- ### Create Empty AudioSegment Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Initialize a zero-duration segment, useful for initializing aggregation loops. ```python from pydub import AudioSegment empty = AudioSegment.empty() len(empty) == 0 ``` ```python from pydub import AudioSegment sounds = [ AudioSegment.from_wav("sound1.wav"), AudioSegment.from_wav("sound2.wav"), AudioSegment.from_wav("sound3.wav"), ] playlist = AudioSegment.empty() for sound in sounds: playlist += sound ``` -------------------------------- ### Generate Audio Signals Source: https://context7.com/jiaaro/pydub/llms.txt Create various waveforms programmatically and export them as audio segments or files. ```python from pydub.generators import Sine, Square, Sawtooth, Triangle, WhiteNoise, Pulse # Generate a 440 Hz sine wave (A4 note) for 1 second sine_wave = Sine(440).to_audio_segment(duration=1000) # Generate at specific sample rate and bit depth high_quality_sine = Sine(440, sample_rate=48000, bit_depth=24).to_audio_segment( duration=1000, volume=-3.0 # -3 dB below max ) # Square wave (harsh, buzzy sound) square_wave = Square(440).to_audio_segment(duration=1000) # Pulse wave with custom duty cycle (25%) pulse_wave = Pulse(440, duty_cycle=0.25).to_audio_segment(duration=1000) # Sawtooth wave (bright, rich harmonics) sawtooth_wave = Sawtooth(440).to_audio_segment(duration=1000) # Triangle wave (softer than square) triangle_wave = Triangle(440).to_audio_segment(duration=1000) # White noise noise = WhiteNoise().to_audio_segment(duration=1000, volume=-10) # Create a simple melody from pydub import AudioSegment # Note frequencies (A4 = 440 Hz) notes = { 'C4': 261.63, 'D4': 293.66, 'E4': 329.63, 'F4': 349.23, 'G4': 392.00, 'A4': 440.00, 'B4': 493.88, 'C5': 523.25 } # Create a simple scale scale = AudioSegment.empty() for note_name in ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5']: freq = notes[note_name] tone = Sine(freq).to_audio_segment(duration=250, volume=-6) tone = tone.fade_in(10).fade_out(50) scale += tone scale.export("scale.wav", format="wav") # Generate test tones test_1khz = Sine(1000).to_audio_segment(duration=5000, volume=-12) test_1khz.export("test_tone_1khz.wav", format="wav") ``` -------------------------------- ### Clone Pydub repository Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Clone the source code repository for local development. ```bash git clone https://github.com/jiaaro/pydub.git ``` -------------------------------- ### Access Raw Audio Data and NumPy Source: https://context7.com/jiaaro/pydub/llms.txt Extract raw sample data from audio segments for integration with NumPy or custom processing. ```python from pydub import AudioSegment import array import numpy as np sound = AudioSegment.from_file("audio.mp3") # Get samples as Python array samples = sound.get_array_of_samples() # Get array type for the audio format array_type = sound.array_type # 'h' for 16-bit, 'i' for 32-bit, etc. # Get raw bytes raw_bytes = sound.raw_data # Convert to NumPy array samples_array = np.array(samples) # For stereo, reshape to separate channels if sound.channels == 2: samples_array = samples_array.reshape((-1, 2)) left_channel = samples_array[:, 0] right_channel = samples_array[:, 1] # Process with NumPy (example: apply gain) gain_factor = 0.5 processed = (samples_array * gain_factor).astype(np.int16) ``` -------------------------------- ### Export AudioSegment with Metadata Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Export audio to a file path with specific bitrate, tags, and cover art, or split audio into chunks and export to file handles. ```python file_handle = sound.export("/path/to/output.mp3", format="mp3", bitrate="192k", tags={"album": "The Bends", "artist": "Radiohead"}, cover="/path/to/albumcovers/radioheadthebends.jpg") # split sound in 5-second slices and export for i, chunk in enumerate(sound[::5000]): with open("sound-%s.mp3" % i, "wb") as f: chunk.export(f, format="mp3") ``` -------------------------------- ### Set Sample Width of Audio Segment Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Create an equivalent AudioSegment with a specified sample width (in bytes). Increasing sample width can improve dynamic range without reducing quality, while decreasing it can lead to quality loss. ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") # Convert to 2-byte sample width (16-bit audio) set_sample_width_sound = sound1.set_sample_width(2) ``` -------------------------------- ### Export with Custom Parameters Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Pass custom ffmpeg parameters during export. ```python # Use preset mp3 quality 0 (equivalent to lame V0) awesome.export("mashup.mp3", format="mp3", parameters=["-q:a", "0"]) # Mix down to two channels and set hard output volume awesome.export("mashup.mp3", format="mp3", parameters=["-ac", "2", "-vol", "150"]) ``` -------------------------------- ### AudioSegment.from_file Source: https://context7.com/jiaaro/pydub/llms.txt Loads an audio file into an AudioSegment object. Supports various formats and raw PCM data. ```APIDOC ## AudioSegment.from_file ### Description Opens an audio file and returns an AudioSegment instance. This is the primary method for loading audio from various file formats. ### Parameters #### Request Body - **file** (str/file handle) - Required - Path to the audio file or an open file handle. - **format** (str) - Optional - The format of the audio file (e.g., 'wav', 'mp3', 'ogg', 'raw'). - **frame_rate** (int) - Optional - Required for raw files. - **channels** (int) - Optional - Required for raw files. - **sample_width** (int) - Optional - Required for raw files. - **start_second** (int) - Optional - Start time in seconds for partial loading. - **duration** (int) - Optional - Duration in seconds for partial loading. ### Response #### Success Response (200) - **AudioSegment** (object) - An immutable object representing the loaded audio data. ``` -------------------------------- ### Export AudioSegment to a File Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Demonstrates the basic usage of exporting an AudioSegment object to a file in a specified format, such as MP3. The export method returns a file handle of the output file. ```python from pydub import AudioSegment sound = AudioSegment.from_file("/path/to/sound.wav", format="wav") # simple export file_handle = sound.export("/path/to/output.mp3", format="mp3") ``` -------------------------------- ### AudioSegment Set Channels Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Create an equivalent AudioSegment with a specified number of channels. ```APIDOC ## AudioSegment(...).set_channels(channels) ### Description Creates an equivalent version of this `AudioSegment` with the specified number of channels (1 is Mono, 2 is Stereo). Converting from mono to stereo does not cause any audible change. Converting from stereo to mono may result in loss of quality (but only if the left and right channels differ). ### Method `set_channels` ### Parameters #### Arguments - **channels** (int) - The desired number of channels (1 for Mono, 2 for Stereo). ### Request Example ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") # Convert sound1 to stereo sound_stereo = sound1.set_channels(2) # Convert sound1 to mono sound_mono = sound1.set_channels(1) ``` ### Response Returns a new `AudioSegment` with the specified number of channels. ### Response Example ```python # sound_stereo and sound_mono are new AudioSegment objects ``` ``` -------------------------------- ### Overlay and Mix Audio Source: https://context7.com/jiaaro/pydub/llms.txt Combine multiple audio segments by overlaying them at specific positions or looping effects. ```python from pydub import AudioSegment # Load audio files music = AudioSegment.from_file("background_music.mp3") voice = AudioSegment.from_file("voiceover.mp3") # Simple overlay (starts at beginning) mixed = music.overlay(voice) # Overlay with position offset (voice starts at 5 seconds) mixed = music.overlay(voice, position=5000) # Loop the overlay until the base audio ends short_effect = AudioSegment.from_file("effect.mp3") with_looped_effect = music.overlay(short_effect, loop=True) # Repeat overlay a specific number of times with_repeated_effect = music.overlay(short_effect, times=4) # Duck music volume during voiceover (-8 dB during overlay) podcast = music.overlay(voice, position=2000, gain_during_overlay=-8) # Mix multiple layers drums = AudioSegment.from_file("drums.wav") bass = AudioSegment.from_file("bass.wav") guitar = AudioSegment.from_file("guitar.wav") # Create silent canvas and overlay all tracks duration = max(len(drums), len(bass), len(guitar)) mix = AudioSegment.silent(duration=duration, frame_rate=44100) mix = mix.overlay(drums) mix = mix.overlay(bass) mix = mix.overlay(guitar) ``` -------------------------------- ### Audio Export Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Exporting audio to various formats with customizable options like bitrate, tags, and cover images. Also demonstrates splitting audio into chunks and exporting them. ```APIDOC ## Exporting Audio ### Description Exports an AudioSegment to a file or file handle with various customization options. ### Method `AudioSegment.export()` ### Parameters - `output_path_or_handle` (string or file handle) - The path or file handle to write the output to. - `format` (string) - The output file format (e.g., "mp3", "wav"). Requires ffmpeg for formats other than "wav" and "raw". - `bitrate` (string) - The bitrate for compressed formats (e.g., "192k"). Requires ffmpeg. - `tags` (dict) - Media info tags to embed in the file (e.g., `{"album": "The Bends", "artist": "Radiohead"}`). Not all formats support tags. - `cover` (string) - Path to a cover image file. Currently only supported for MP3 format. - `codec` (string) - Specify the audio codec for formats that support multiple codecs (e.g., "libvorbis" for "ogg"). Requires ffmpeg. - `parameters` (list of strings) - Additional command line parameters to pass to ffmpeg. - `id3v2_version` (string) - The ID3v2 version to use for tagging MP3 files (e.g., "3" or "4"). ### Request Example ```python from pydub import AudioSegment sound = AudioSegment.from_wav("/path/to/sound.wav") # Export to MP3 with specific bitrate and tags sound.export("/path/to/output.mp3", format="mp3", bitrate="192k", tags={"album": "The Bends", "artist": "Radiohead"}, cover="/path/to/albumcovers/radioheadthebends.jpg") # Split and export chunks for i, chunk in enumerate(sound[::5000]): with open(f"sound-{i}.mp3", "wb") as f: chunk.export(f, format="mp3") ``` ``` -------------------------------- ### Overlay AudioSegments Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Plays two audio segments simultaneously, with options for positioning, gain adjustment, and looping. ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") sound2 = AudioSegment.from_file("sound2.wav") played_togther = sound1.overlay(sound2) sound2_starts_after_delay = sound1.overlay(sound2, position=5000) volume_of_sound1_reduced_during_overlay = sound1.overlay(sound2, gain_during_overlay=-8) sound2_repeats_until_sound1_ends = sound1.overlay(sound2, loop=true) sound2_plays_twice = sound1.overlay(sound2, times=2) ``` -------------------------------- ### Convert video files to MP3 Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Batch convert MP4 and FLV files in a directory to MP3 format. ```python 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') ``` -------------------------------- ### Set Channels of Audio Segment Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Create an equivalent AudioSegment with a specified number of channels (1 for Mono, 2 for Stereo). Converting from mono to stereo does not affect quality, but stereo to mono may result in quality loss if channels differ. ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") # Convert to stereo (2 channels) set_channels_sound = sound1.set_channels(2) ``` -------------------------------- ### Create Multi-channel AudioSegment Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Combine multiple mono segments of equal length into a single multi-channel segment. ```python from pydub import AudioSegment left_channel = AudioSegment.from_wav("sound1.wav") right_channel = AudioSegment.from_wav("sound1.wav") stereo_sound = AudioSegment.from_mono_audiosegments(left_channel, right_channel) ``` -------------------------------- ### Export Audio Files with AudioSegment.export Source: https://context7.com/jiaaro/pydub/llms.txt Use `AudioSegment.export` to save audio to various formats. Options include setting bitrate, metadata tags, codec, cover art (MP3 only), and custom FFmpeg parameters. It can also export to file handles or split and export chunks. ```python from pydub import AudioSegment sound = AudioSegment.from_file("input.wav") # Simple export to MP3 sound.export("output.mp3", format="mp3") # Export with bitrate and metadata tags sound.export( "output.mp3", format="mp3", bitrate="192k", tags={ "artist": "Artist Name", "album": "Album Title", "title": "Song Title", "genre": "Rock" } ) # Export OGG with specific codec sound.export("output.ogg", format="ogg", codec="libvorbis") # Export with cover art (MP3 only) sound.export( "output.mp3", format="mp3", cover="album_cover.jpg" ) # Export with custom FFmpeg parameters sound.export( "output.mp3", format="mp3", parameters=["-q:a", "0"] # VBR quality 0 (best) ) # Export raw PCM data sound.export("output.raw", format="raw") # Export to file handle with open("output.mp3", "wb") as f: sound.export(f, format="mp3") # Split and export chunks for i, chunk in enumerate(sound[::5000]): # 5-second chunks chunk.export(f"chunk_{i}.mp3", format="mp3") ``` -------------------------------- ### Access Audio Properties and Metadata Source: https://context7.com/jiaaro/pydub/llms.txt Retrieve technical details about an audio file including duration, sample rate, and raw data. ```python from pydub import AudioSegment sound = AudioSegment.from_file("audio.mp3") # Duration duration_ms = len(sound) # Duration in milliseconds duration_sec = sound.duration_seconds # Duration in seconds # Audio format properties channels = sound.channels # 1 = mono, 2 = stereo sample_width = sound.sample_width # Bytes per sample (2 = 16-bit) frame_rate = sound.frame_rate # Sample rate (e.g., 44100 Hz) frame_width = sound.frame_width # Bytes per frame (channels * sample_width) # Loudness measurements dbfs = sound.dBFS # Average loudness in dB relative to full scale rms = sound.rms # RMS amplitude max_amplitude = sound.max # Peak sample value max_dbfs = sound.max_dBFS # Peak amplitude in dBFS # Frame information total_frames = sound.frame_count() # Total number of frames frames_in_1sec = sound.frame_count(ms=1000) # Frames in 1 second # Raw data access raw_bytes = sound.raw_data # Raw audio data as bytes samples = sound.get_array_of_samples() # Audio data as array ``` -------------------------------- ### AudioSegment Channel and Gain Methods Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Methods for splitting stereo channels, applying gain, and panning audio. ```APIDOC ## AudioSegment.split_to_mono() ### Description Splits a stereo AudioSegment into two, one for each channel (Left/Right). ### Method Method Call ### Response - **list** (list) - A list containing two AudioSegment objects: index 0 is the left channel, index 1 is the right channel. ## AudioSegment.apply_gain_stereo(left_gain, right_gain) ### Description Apply gain to the left and right channel of a stereo AudioSegment. If the segment is mono, it is converted to stereo first. ### Parameters #### Arguments - **left_gain** (float) - Required - Gain in dB for the left channel. - **right_gain** (float) - Required - Gain in dB for the right channel. ## AudioSegment.pan(pan_amount) ### Description Adjusts the stereo balance of the audio. ### Parameters #### Arguments - **pan_amount** (float) - Required - Value between -1.0 (100% left) and +1.0 (100% right). ``` -------------------------------- ### Set Frame Rate of Audio Segment Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Create an equivalent AudioSegment with a specified frame rate (in Hz). Increasing frame rate can improve frequency response, while decreasing it can lead to quality loss. ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") # Convert to 44100 Hz frame rate set_frame_rate_sound = sound1.set_frame_rate(44100) ``` -------------------------------- ### Debug Pydub Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Configure logging to inspect the underlying subprocess calls made to ffmpeg. ```python >>> import logging >>> l = logging.getLogger("pydub.converter") >>> l.setLevel(logging.DEBUG) >>> l.addHandler(logging.StreamHandler()) >>> AudioSegment.from_file("./test/data/test1.mp3") subprocess.call(['ffmpeg', '-y', '-i', '/var/folders/71/42k8g72x4pq09tfp920d033r0000gn/T/tmpeZTgMy', '-vn', '-f', 'wav', '/var/folders/71/42k8g72x4pq09tfp920d033r0000gn/T/tmpK5aLcZ']) ``` -------------------------------- ### AudioSegment Set Frame Rate Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Create an equivalent AudioSegment with a specified frame rate. ```APIDOC ## AudioSegment(...).set_frame_rate(rate) ### Description Creates an equivalent version of this `AudioSegment` with the specified frame rate (in Hz). Increasing this value does not generally cause a reduction in quality. Reducing it *definitely* causes a loss in quality. Higher frame rate means larger frequency response (higher frequencies can be represented). ### Method `set_frame_rate` ### Parameters #### Arguments - **rate** (int) - The desired frame rate in Hz (e.g., 44100). ### Request Example ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") # Convert sound1 to a frame rate of 44100 Hz sound_44100hz = sound1.set_frame_rate(44100) ``` ### Response Returns a new `AudioSegment` with the specified frame rate. ### Response Example ```python # sound_44100hz is a new AudioSegment object ``` ``` -------------------------------- ### Measure Audio Loudness Source: https://context7.com/jiaaro/pydub/llms.txt Calculate various loudness metrics like dBFS, RMS, and peak amplitude for an AudioSegment. ```python loudness_dbfs = sound.dBFS # Average loudness in dBFS peak_amplitude = sound.max # Peak sample value peak_dbfs = sound.max_dBFS # Peak in dBFS rms_value = sound.rms # RMS loudness # Normalize to a target headroom target_dbfs = -14.0 change_in_dbfs = target_dbfs - sound.dBFS normalized = sound.apply_gain(change_in_dbfs) # Manual peak normalization normalized = sound.apply_gain(-sound.max_dBFS) # Normalize to 0 dBFS peak ``` -------------------------------- ### Convert Audio to Float32 Samples Source: https://context7.com/jiaaro/pydub/llms.txt Converts an AudioSegment to a NumPy array of float32 samples, setting the frame rate to 16000 Hz and channels to 1. This is useful for machine learning or digital signal processing tasks. ```python import numpy as np from pydub import AudioSegment def audio_to_float32(sound): sound = sound.set_frame_rate(16000).set_channels(1) samples = np.array(sound.get_array_of_samples()) return samples.astype(np.float32) / np.iinfo(np.int16).max float_samples = audio_to_float32(sound) ``` -------------------------------- ### Silence Detection and Manipulation Source: https://context7.com/jiaaro/pydub/llms.txt Detects silent regions, splits audio based on silence thresholds, and generates silent segments. ```python from pydub import AudioSegment from pydub.silence import ( detect_silence, detect_nonsilent, split_on_silence, detect_leading_silence ) sound = AudioSegment.from_file("audio.mp3") # Detect all silent sections (returns list of [start, end] in ms) silent_ranges = detect_silence( sound, min_silence_len=1000, # Minimum 1 second of silence silence_thresh=-40, # Silence threshold in dBFS seek_step=10 # Check every 10ms (faster but less precise) ) print(f"Silent sections: {silent_ranges}") # Detect all non-silent sections nonsilent_ranges = detect_nonsilent( sound, min_silence_len=500, silence_thresh=-40 ) print(f"Non-silent sections: {nonsilent_ranges}") # Split audio on silence (returns list of AudioSegments) chunks = split_on_silence( sound, min_silence_len=700, # Split on silences longer than 700ms silence_thresh=-40, # Silence threshold keep_silence=200 # Keep 200ms of silence at edges ) # Export each chunk for i, chunk in enumerate(chunks): chunk.export(f"chunk_{i}.mp3", format="mp3") # Detect leading silence duration leading_silence_ms = detect_leading_silence( sound, silence_threshold=-50, chunk_size=10 ) print(f"Leading silence: {leading_silence_ms}ms") # Trim leading and trailing silence start_trim = detect_leading_silence(sound) end_trim = detect_leading_silence(sound.reverse()) trimmed = sound[start_trim:len(sound)-end_trim] # Create silent audio one_second_silence = AudioSegment.silent(duration=1000) silence_cd_quality = AudioSegment.silent(duration=5000, frame_rate=44100) ``` -------------------------------- ### AudioSegment Creation Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Creating new AudioSegments, including empty segments, silent segments, and multi-channel segments from mono sources. ```APIDOC ## Creating AudioSegments ### AudioSegment.empty() Creates a zero-duration `AudioSegment`. #### Parameters None #### Request Example ```python from pydub import AudioSegment empty_segment = AudioSegment.empty() print(len(empty_segment) == 0) ``` ### AudioSegment.silent() Creates a silent `AudioSegment`. #### Parameters - `duration` (int) - Length of the silent segment in milliseconds. Default is 1000 (1 second). - `frame_rate` (int) - Frame rate (sample rate) of the silent segment in Hz. Default is 11025. #### Request Example ```python from pydub import AudioSegment silent_segment = AudioSegment.silent(duration=10000) # 10 seconds of silence ``` ### AudioSegment.from_mono_audiosegments() Creates a multi-channel `AudioSegment` from multiple mono `AudioSegment`s. #### Parameters - `*mono_segments` (AudioSegment) - Two or more mono `AudioSegment`s of the same length. #### Request Example ```python from pydub import AudioSegment left_channel = AudioSegment.from_wav("left.wav") right_channel = AudioSegment.from_wav("right.wav") stereo_sound = AudioSegment.from_mono_audiosegments(left_channel, right_channel) ``` ``` -------------------------------- ### Print Audio Metadata Source: https://context7.com/jiaaro/pydub/llms.txt Displays basic audio information such as duration, channels, sample rate, bit depth, and loudness. ```python print(f"Duration: {duration_sec:.2f} seconds") print(f"Channels: {channels}") print(f"Sample Rate: {frame_rate} Hz") print(f"Bit Depth: {sample_width * 8} bits") print(f"Loudness: {dbfs:.1f} dBFS") ``` -------------------------------- ### Check Duration Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Retrieve the duration of an audio segment in seconds. ```python without_the_middle.duration_seconds == 15.0 ``` -------------------------------- ### Export Audio Source: https://github.com/jiaaro/pydub/blob/master/README.markdown Export audio segments to various formats with optional metadata and bitrate settings. ```python awesome.export("mashup.mp3", format="mp3") ``` ```python awesome.export("mashup.mp3", format="mp3", tags={'artist': 'Various artists', 'album': 'Best of 2011', 'comments': 'This album is awesome!'}) ``` ```python awesome.export("mashup.mp3", format="mp3", bitrate="192k") ``` -------------------------------- ### AudioSegment Overlay Source: https://github.com/jiaaro/pydub/blob/master/API.markdown Overlay one AudioSegment onto another with options for positioning, looping, and repetition. ```APIDOC ## AudioSegment(...).overlay(other, position=0, loop=False, times=1, gain_during_overlay=0) ### Description Overlay another `AudioSegment` onto this one. This method is useful for mixing sounds, adding sound effects, or creating layered audio. ### Method `overlay` ### Parameters #### Keyword Arguments - **other** (AudioSegment) - The `AudioSegment` to overlay. - **position** (int) - Optional. The time in milliseconds from the beginning of this `AudioSegment` where the overlay will begin. Defaults to 0 (beginning). - **loop** (bool) - Optional. If True, the overlaid `AudioSegment` will repeat starting from the `position` until the end of this `AudioSegment`. Defaults to False. - **times** (int) - Optional. The overlaid `AudioSegment` will repeat this many times starting from `position`, but will still be truncated to the length of this `AudioSegment`. Defaults to 1. - **gain_during_overlay** (float) - Optional. Change the original audio's volume by this many dB while overlaying. A negative value makes the original audio quieter. Defaults to 0 (no change). ### Example ```python from pydub import AudioSegment sound1 = AudioSegment.from_file("sound1.wav") # Assume 30 sec long sound2 = AudioSegment.from_file("sound2.wav") # Assume 5 sec long # Overlay sound2 onto sound1 10000 times (effectively just once, truncated to sound1's length) sound2_plays_a_lot = sound1.overlay(sound2, times=10000) # Overlay sound2 starting at 3 seconds (3000 ms) into sound1, looping until sound1 ends sound1_with_looping_effect = sound1.overlay(sound2, position=3000, loop=True) ``` ```