Package: pozalabs-pydub
PydubPydub lets you do stuff to audio in a way that isn't stupid.Stuff you might be looking for:Installing PydubAPI DocumentationDependenciesPlaybackSetting up ffmpegQuestions/BugsQuickstartOpen a WAV filefrompydubimportAudioSegmentsong=AudioSegment.from_wav("never_gonna_give_you_up.wav")...or a mp3song=AudioSegment.from_mp3("never_gonna_give_you_up.mp3")... or an ogg, or flv, oranything else ffmpeg supportsogg_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 millisecondsten_seconds=10*1000first_10_seconds=song[:ten_seconds]last_5_seconds=song[-5000:]Make the beginning louder and the end quieter# boost volume by 6dBbeginning=first_10_seconds+6# reduce volume by 3dBend=last_5_seconds-3Concatenate audio (add one file to the end of another)without_the_middle=beginning+endHow long is it?without_the_middle.duration_seconds==15.0AudioSegments are immutable# song is not modifiedbackwards=song.reverse()Crossfade (again, beginning and end are not modified)# 1.5 second crossfadewith_style=beginning.append(end,crossfade=1500)Repeat# repeat the clip twicedo_it_over=with_style*2Fade (note that you can chain operations because everything returns
an AudioSegment)# 2 sec fade in, 3 sec fade outawesome=do_it_over.fade_in(2000).fade_out(3000)Save the results (again whatever ffmpeg supports)awesome.export("mashup.mp3",format="mp3")Save the results with tags (metadata)awesome.export("mashup.mp3",format="mp3",tags={'artist':'Various artists','album':'Best of 2011','comments':'This album is awesome!'})You can pass an optional bitrate argument to export using any syntax ffmpeg
supports.awesome.export("mashup.mp3",format="mp3",bitrate="192k")Any further arguments supported by ffmpeg can be passed as a list in a
'parameters' argument, with switch first, argument second. Note that no
validation takes place on these parameters, and you may be limited by what
your particular build of ffmpeg/avlib supports.# 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 volumeawesome.export("mashup.mp3",format="mp3",parameters=["-ac","2","-vol","150"])DebuggingMost issues people run into are related to converting between formats using
ffmpeg/avlib. Pydub provides a logger that outputs the subprocess calls to
help you track down issues:>>>importlogging>>>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'])<pydub.audio_segment.AudioSegmentobjectat0x101b43e10>Don't worry about the temporary files used in the conversion. They're cleaned up
automatically.Bugs & QuestionsYou can file bugs in ourgithub issues tracker,
and ask any technical questions onStack Overflow using the pydub tag.
We keep an eye on both.InstallationInstalling pydub is easy, but don't forget to install ffmpeg/avlib (the next section in this doc)pip install pydubOr install the latest dev version from github (or replace@masterwith arelease version like@v0.12.0)…pip install git+https://github.com/jiaaro/pydub.git@master-OR-git clone https://github.com/jiaaro/pydub.git-OR-Copy the pydub directory into your python path. ZiphereDependenciesYou can open and save WAV files with pure python. For opening and saving non-wav
files – like mp3 – you'll needffmpegorlibav.PlaybackYou can play audio if you have one of these installed (simpleaudiostronglyrecommended, even if you are installing ffmpeg/libav):simpleaudiopyaudioffplay (usually bundled with ffmpeg, see the next section)avplay (usually bundled with libav, see the next section)frompydubimportAudioSegmentfrompydub.playbackimportplaysound=AudioSegment.from_file("mysound.wav",format="wav")play(sound)Getting ffmpeg set upYou may uselibav or ffmpeg.Mac (usinghomebrew):# libavbrewinstalllibav####    OR    ###### ffmpegbrewinstallffmpegLinux (using aptitude):# libavapt-getinstalllibav-toolslibavcodec-extra####    OR    ###### ffmpegapt-getinstallffmpeglibavcodec-extraWindows:Download and extract libav fromWindows binaries provided here.Add the libav/binfolder to your PATH envvarpip install pydubImportant NotesAudioSegmentobjects areimmutableOgg exporting and default codecsThe Ogg specification (http://tools.ietf.org/html/rfc5334) does not specify
the codec to use, this choice is left up to the user. Vorbis and Theora are just
some of a number of potential codecs (see page 3 of the rfc) that can be used for the
encapsulated data.When no codec is specified exporting tooggwilldefaultto usingvorbisas a convenience. That is:frompydubimportAudioSegmentsong=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")Example UseSuppose you have a directory filled withmp4andflvvideos and you want to convert all of them tomp3so you can listen to  them on your mp3 player.importosimportglobfrompydubimportAudioSegmentvideo_dir='/home/johndoe/downloaded_videos/'# Path where the videos are locatedextension_list=('*.mp4','*.flv')os.chdir(video_dir)forextensioninextension_list:forvideoinglob.glob(extension):mp3_filename=os.path.splitext(os.path.basename(video))[0]+'.mp3'AudioSegment.from_file(video).export(mp3_filename,format='mp3')How about another example?fromglobimportglobfrompydubimportAudioSegmentplaylist_songs=[AudioSegment.from_mp3(mp3_file)formp3_fileinglob("*.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_songforsonginplaylist_songs:# We don't want an abrupt stop at the end, so let's do a 10 second crossfadesplaylist=playlist.append(song,crossfade=(10*1000))# let's fade out the end of the last songplaylist=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!withopen("%s_minute_playlist.mp3"%playlist_length,'wb')asout_f:playlist.export(out_f,format='mp3')License (MIT License)Copyright © 2011 James Robert,http://jiaaro.comPermission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.