Last active
December 27, 2019 20:15
-
-
Save jamiebullock/fbf6684e69f8a66aac9c1d40a039185e to your computer and use it in GitHub Desktop.
PyDub demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib.request | |
from pydub import AudioSegment | |
from pydub.playback import play | |
from pydub.generators import Sine | |
# Download an audio file | |
urllib.request.urlretrieve("https://tinyurl.com/wx9amev", "metallic-drums.wav") | |
# Load into PyDub | |
loop = AudioSegment.from_wav("metallic-drums.wav") | |
# Repeat 2 times | |
loop2 = loop * 2 | |
# Get length in milliseconds | |
length = len(loop2) | |
# Set fade time | |
fade_time = int(length * 0.5) | |
# Fade in and out | |
faded = loop2.fade_in(fade_time).fade_out(fade_time) | |
# Play the faded loop | |
play(faded) | |
# Download another loop | |
urllib.request.urlretrieve("https://tinyurl.com/yx3k5kw5", "beat.wav") | |
# Load into PyDub | |
beat = AudioSegment.from_wav("beat.wav") | |
# Filter the beat at 2kHz | |
filtered = beat.low_pass_filter(3000) | |
# Mix loop2 with a reversed version | |
loop2 = loop2.reverse().pan(-0.5).overlay(loop2.pan(0.5)) | |
# Mix our filtered beat with the new loop2 | |
final = filtered.overlay(loop2-3, loop=True) | |
# Play the result | |
play(final) | |
# Save the result to an MP3 file | |
final.export("final.mp3", format="mp3") | |
# Create an empty segment to store our result | |
result = AudioSegment.silent(duration=0) | |
# Loop over 0-14 | |
for n in range(15): | |
# Generate a sine tone with frequency 200 * n | |
gen = Sine(200 * n) | |
# Turn the tone into an AudioSegment with duration 200ms and gain -3 | |
sine = gen.to_audio_segment(duration=200).apply_gain(-3) | |
# Fade in / out | |
sine = sine.fade_in(50).fade_out(100) | |
# Append the sine to our result | |
result += sine | |
# Play the result | |
play(result) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment