31

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) )

xxjjnn
  • 14,591
  • 19
  • 61
  • 94

4 Answers4

39

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")
Jiaaro
  • 74,485
  • 42
  • 169
  • 190
  • 1
    @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 – Jiaaro Feb 25 '14 at 17:22
  • This what worked for me: `song.export(mp3_path, format="mp3", codec="libmp3lame")` – SpiralDev Jun 04 '20 at 08:57
20

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)
Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
  • 1
    After hours of trying on-line methods to save audio in a compressed format like `mp3` or `ogg` from WAV-PCM data, this solution is the only one that have worked for me on Windows 10. – Vichoko Oct 26 '19 at 06:40
12

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")
Abhishek Rathore
  • 1,016
  • 1
  • 11
  • 13
-14

will you can just rename the file extension , i think os library will help you any way i will give you example :

yourfile.wav ==>> yourfile.mp3 or any type that is for audio and video file

for me it's worked !!

David
  • 9
  • 4
  • 2
    If 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. – colidyre Apr 13 '20 at 03:19