Python convert wav to mp3
Solution 1
using lame (command line), you can encode wav to mp3 like this:
$ lame --preset insane /path/to/file.wav
which would create:
file.wav.mp3
in Python, you could use subprocess to call it:
wav = 'myfile.wav'
cmd = 'lame --preset insane %s' % wav
subprocess.call(cmd, shell=True)
Solution 2
I wrote a python library, pydub, that essentially does what Corey's Answer suggests, though it uses ffmpeg in to do the conversions in order to support more formats.
from pydub import AudioSegment
AudioSegment.from_wav("/input/file.wav").export("/output/file.mp3", format="mp3")
Solution 3
You must go for pydub, it is a great module for operations related with audio files.
NOTE. Do remember to install ffmpeg before you use pydub.
For help regarding installation of ffmpeg, you can use this link.
Then to install pydub just open your command prompt and type
pip install pydub
Then to convert any file from wav to mp3 just use pydub as
import pydub
sound = pydub.AudioSegment.from_wav("D:/example/apple.wav")
sound.export("D:/example/apple.mp3", format="mp3")
Related videos on Youtube
xxjjnn
Programmer Otaku Former PTI Pic unrelated - Calvin and Hobbes Moniker arbitrary - real name Joe Nelson
Updated on April 13, 2020Comments
-
xxjjnn about 4 years
I've looked at pymedia (discontinued), pyglet(great but no converter in there) and audiotools(command line cd ripping), and none seem suitable.
In Python 2.7 , how do you do
convert(wavFileLocation, 'mp3')
If there is no python way, how would you do it in a manner which python can invoke? (e.g. Call a Cross platform command line tool... if exists return (name, pythonCodeForInvocation) )
-
g19fanatic about 12 yearswhich OS? Linux has some great command line utilities that would allow you to do this without much issue.
-
xxjjnn about 12 yearsLinux =) But it needs to run on mac too
-
g19fanatic about 12 yearsfor linux, this solution gives you an answer stackoverflow.com/a/6578380/496405 use ffmpeg should also work under mac :)
-
-
Jiaaro about 10 years@Basj Not currently, no - you'd need to save the wav data to a file on disk, and then convert it to mp3 afterward. There has been some discussion about support for operating on steams/iterators, but nothing has come to fruition so far
-
Vichoko over 4 yearsAfter hours of trying on-line methods to save audio in a compressed format like
mp3
orogg
from WAV-PCM data, this solution is the only one that have worked for me on Windows 10. -
colidyre about 4 yearsIf you rename it, there is only another name. But it is not really converted. A wav file is something different than a mp3 file, even if you name it like a mp3 file.
-
SpiralDev almost 4 yearsThis what worked for me:
song.export(mp3_path, format="mp3", codec="libmp3lame")