How to convert MP3 to WAV in Python - python

If I have an MP3 file how can I convert it to a WAV file? (preferably, using a pure python approach)

I maintain an open source library, pydub, which can help you out with that.
from pydub import AudioSegment
sound = AudioSegment.from_mp3("/path/to/file.mp3")
sound.export("/output/path/file.wav", format="wav")
One caveat: it uses ffmpeg to handle audio format conversions (except for wav files, which python handles natively).
note: you probably shouldn't do this conversion on GAE :/ even if it did support ffmpeg. EC2 would be a good match for the job though

This is working for me:
import subprocess
subprocess.call(['ffmpeg', '-i', 'audio.mp3',
'audio.wav'])

I think I am right person to answer this question because I am student who tried hard to get answer for this question. I am giving answer for Windows users but I think this may work with MAC OS too. But apt for windows.
Lets discuss answers in steps:
first check for pydub and ffmpeg package. If you computer dont have these packages then install pydub in you command prompt
pip install pydub
Next and imp thing is ffmpeg package which converts images to different formats. For this you should manually install this package. Let me give you reason why when we can use pip for installing package. First pip installs the package but it will not stores the path to the system. So computer cant recognize this package path. For this I suggest you to install manually but how.... dont worry will give you steps.
STEP 1:
#Present link
This first link that you have paste it in google
https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip
#Use for future students
But people will have question now this link might work what about future. For that simple answer is
https://www.gyan.dev/ffmpeg/builds/
After typing this in google go to releases and download zip folder always don't download 7.zip.But thus is only when my first link will not work for future is any student search for answer.
STEP 2: After downloading the zip file from first step first link. Now make a folder in C drive. For this just click on my My PC, then OS(C:),make a new folder. Copy paste the zip file downloaded to this folder. Extract the zip file in this new folder. Now go into the folder and copy path of "bin" present in this folder from properties.
STEP 3:This is final step and imp one where you will set path. In search bar in your laptop search for "Edit the system environmental variables". Then click on "environmental variables" at bottom for path. Here they are two parts in screen system variables and user variables. Now you have to search for path "Path" in system variable is you want to use for whole system. Double click on "Path" in system variables. A window appears where you have to choose "New". Here copy paste the path of bin folder. Then click on Ok in all and close all tabs.
Step 4:Check for correct installation of ffmpeg. In command prompt type ffmpeg now you will get the list of paths and its features. This shows you have finished your installation.
Step 5 : Download a mp3 file. If your have downloaded python then open IDLE prompt. The click on new in File a note pad appears. One imp point to remember here is copy paste the mp3 file where you python code is stored. Example If I want to save the python file in Desktop the mp3 file should be stored in desktop. I think you go an idea. Now copy paste the code which I am using
import subprocess
subprocess.call(['ffmpeg', '-i', 'ind.mp3','ind1.wav'])
then click on run module
you will get the conversion.
Thank you
This answer might help you. If you want code and method for converting speech to text code and method you can post me. I wish this answer for 10 min may save you hours.
https://www.youtube.com/watch?v=vBb_eYThfRQ
use this video for path configuration or step 3 for reference but copy path to system variables not user because whole system can use this package then. If my language is bad don't mind I think it is understandable.

Install the module pydub. This is an audio manipulation module for Python. This module can open many multimedia audio and video formats. You can install this module with pip.
pip install pydub
If you have not installed ffmpeg yet, install it. You can use your package manager to do that.
For Ubuntu / Debian Linux:
apt-get install ffmpeg
When ready, execute the below code:
from os import path
from pydub import AudioSegment
# files
src = "transcript.mp3"
dst = "test.wav"
# convert wav to mp3
sound = AudioSegment.from_mp3(src)
sound.export(dst, format="wav")
Check this link for details.

For Those using windows 7 and above:
Step 1: This link will help you install ffmpeg:
How to Install FFMPEG on Windows
Step 2: This code will help you convert multiple files from one format to another ( which of course is supported by ffmpeg)
import os
import subprocess
input_dir = r'C:\\Path\\To\\Your\\Input\\Directory\\'
output_dir = r'C:\\Path\\To\\Your\\Output\\Directory\\'
path_to_ffmpeg_exe = r'C:\\Path\\To\\ffmpeg-2022-YY-MM-git-blabla-full_build\\bin\\ffmpeg.exe'
files_list = []
for path in os.listdir(input_dir):
if os.path.isfile(os.path.join(input_dir, path)):
files_list.append(path)
for file_nm in files_list:
print(file_nm)
subprocess.call([path_to_ffmpeg_exe, '-i', os.path.join(input_dir, file_nm), os.path.join(output_dir, str(file_nm.split(".")[0] + ".wav"))])

Related

FileNotFoundError: [Errno 2] No such file or directory: 'ffprobe': 'ffprobe'

When running the code snippet, I get the error seen in the title.
I have re-installed the package pydub,and pip3 install ffprobe.
from pydub.playback import play
from pydub import AudioSegment
def change_volume(file_name, alteration):
song = AudioSegment.from_mp3(file_name)
new_song = song + alteration
new_title = ("_%s") % (file_name)
new_song.export(new_title, format='mp3')
change_volume("test_sample.mp3", 3)
The output of the code should be a new mp3 file in the directory with slightly risen volume levels (test.mp3 --> _test.mp3), instead I get the error:
FileNotFoundError: [Errno 2] No such file or directory: 'ffprobe': 'ffprobe'
First make sure you have ffprobe installed, which is part of FFmpeg, so actually you need to install ffmpeg. You can do that by following the instructions of one of those two sites.
https://ffmpeg.org/download.html
https://github.com/adaptlearning/adapt_authoring/wiki/Installing-FFmpeg
After that you need to add the libary to your system path for python to be able to find and to use it. That can be done by either actually adding the installation path of FFmpeg to your OS path (How to do that depends on your operating system), or by adding it to the temporary path variable that is used inside of python.
import sys
sys.path.append('/path/to/ffmpeg')
For the second option you have to make sure to append the path to FFmpeg before importing anything else. This is the better option if you have no option to change the configuration of the root system, but can become very inconsistent when used by different python scripts.
Finally make sure to have ffprobe installed (e.g. with pip install ffprobe inside a terminal, see https://pypi.org/project/ffprobe) so that import ffprobe should work inside the python environment.
I tried the following method, and it worked:
$ sudo apt update
$ sudo apt install ffmpeg
(I'm on a Mac, using Anaconda3.)
Everyone keeps saying add ffmpeg or ffprobe to your path, but to be clear this means add the executable file to your path (not the directory, not the .py file, or anything else). For some reason, even after pip installing/updating and installing/updating via homebrew both ffmpeg and ffprobe, there were no executable files on my system for either. This seems odd; I have no idea why this might be, but here's how I got it to work:
Go to https://ffbinaries.com/downloads and download the zips of both ffmpeg and ffprobe for your system.
Unzip the files to get the executable files.
Move the executable files to the correct path, which for me was "usr/anaconda3/bin" (this directory primarily has executable files). As others have said, you can check your path using import os; print(os.environ['PATH']).
Manually open each of those two executable files from Finder, just so you can give permission to open the file from an unknown developer (i.e. from the ffbinaries site).
That's what finally did it for me, anyway. Hope that helps someone else with the same problem.
I was install ffmpeg through this comamnd inside my docker container "pip3 install ffmpeg-python" and I got this error too,
then I install it through apt-get -> apt-get install ffmpeg
and everything is worked fine
On my Mac, ffmpeg was installed at /usr/local/bin instead of /usr/bin. I added this function which adds my actual path to ffmpeg to the System PATH while the python app is running. This allowed pydub to find it.
def add_usr_local_bin():
ffmpeg_path = "/usr/local/bin"
os.environ["PATH"] += os.pathsep + ffmpeg_path
You can try following command
apt-get install -y ffpmeg

How to unzip .rar file with Python and patoolib

I need uncompress .rar file in Google Colab with Python3. First I tried to do localy in MacOS.
I have installed Patoolib package:
pip install patool
and unrar to unzip .rar files
brew install unrar
Then, In my python script I do:
import patoolib
patoolib.extract_archive("data_2/Peliculas.rar", outdir="/data_2")
and I get the following error :
PatoolError: could not find an executable program to extract format rar; candidates are (rar,unrar,7z),
I need to configure Patool to use unrar but there is no documentation available. Somebody knows how to solve this error?
My issue was solved by simply adding my Winrar directory to my Path (in system environment variables). Made the horrible mistake of assuming it was set up by default (because why wouldn't it, it's already on the contextual menus right?), but that was not the case.
Hope this helps whoever reads this

Downloading multiple .SAO files via http via Python3

I need to use python3 to download multiple .SAO files from http. Each file has a distinct url which differs by a number in the url (for example, https://www.1.SAO, https://www.2.SAO, etc.). How do I achieve this, and how do I control where the files will be downloaded to?
Downloading a file is pretty simple using wget, and changing the URL can be done by modifying the string before executing the download() function.
to install wget, do pip install wget which will install wget to your default python instance. After that, just import it and you're good to go!
For example, if I wanted to download the .sao files from 1 to 10:
import wget
for i in range(1,11):
url = "https://www.{0}.SAO".format(i) #adds the value of "i" in at "{0}"
wget.download(url)
this will download all the files between https://www.1.SAO and https://www.10.SAO and save it to the working directory of the script.
If you wanted to change the directory, wget.download() has an optional second argument. For example, if I wanted to save my file to a directory called downloads which is located in the same directory as the script, I could call:
wget.download(url,"downloads/")
It would then save all my files in that subdirectory, instead of the working directory. If my directory is in an entire different part of the system (Let's say I wanted to download them to /usr/bin/ or something, I can specify that as well, the same way as using a normal Unix file path:
wget.download(url,"/usr/bin/")
Hopefully this helps you get started.

Installing Scraperwiki for Python generates an error pdftohtml not found

I have been trying to install Scraperwiki module for Python. However, it generates the error:
""UserWarning: Local Scraperlibs requires pdftohtml, but pdftohtml was not found in the PATH. You probably need to install it".
I looked into poppler as they have pdftohtml file but I don't know how it works - whether there is a python library I need to install or a .exe file. And how do I go about installing it. Running on Windows.
Many Thanks
If you're not intending to use scraperwiki.pdftoxml(), then the warning doesn't apply. It doesn't stop you from installing the scraperwiki package, however.
Also, that function doesn't work on Windows at all as is; it uses NamedTemporaryFiles which behave differently on Windows to Linux.
If you do want to use that function, the simplest way to get an up-to-date version of pdftohtml on Windows is to download Calibre Portable. (The version on Sourceforge is older.)
Install it anywhere; you just need a few files from it. From where you installed it, from the folder containing calibre.exe, you need pdftohtml.exe into your working folder as well as, from the DLLs folder in the Calibre install, freetype.dll, jpeg.dll, libpng12.dll, zlib1.dll.
You'll also need code based on scraperwiki.pdftoxml() instead, like:
def pdftoxml(pdfdata, options):
"""converts pdf file to xml file"""
# lots of hacky Windows fixes c.f. original
with open('input.pdf', 'wb') as f:
f.write(pdfdata)
cmd = 'pdftohtml -xml -nodrm -zoom 1.5 -enc UTF-8 -noframes '
if options:
cmd += options
cmd += 'input.pdf output.xml'
cmd = cmd + " > NUL 2>&1"
os.system(cmd)
with open('output.xml', 'r') as f:
return f.read()
(I was trying to get this working for a user in Windows recently; I'll keep the gist containing this code updated.)

Pydub (WindowsError: [Error 2] The system can not find the file specified)

I have a problem with Pydub module running in Windows and Linux. When I try open a mp3 file thus:
from pydub import AudioSegment
sound = AudioSegment.from_mp3("test.mp3")
Console show me the next message:
WindowsError: [Error 2] The system can not find the file specified
But...I have the file (test.mp3) in the same folder that the script, the name is correct.
Why I have this problem? (In Linux, have the same error)
Make sure that you have ffmpeg http://www.ffmpeg.org/ installed. You can get help from this official page.
Other thing that I can think of is that ffmpeg is installed and is in your path but not in the path of the process using pydub.
If this is the reason for the error, then you can set the absolute path to ffmpeg directly like shown below:
import pydub
pydub.AudioSegment.ffmpeg = "/absolute/path/to/ffmpeg"
sound = AudioSegment.from_mp3("test.mp3")
Give this a try.
The other way is put ffmpeg.exe,ffplay.exe in the current working directory
In jupyter notebook this error could persist since the error is with anaconda environment. You can solve this by installing ffmpeg from conda-forge
Got to anaconda prompt and type:
conda install -c conda-forge ffmpeg
In newer versions of pydub, you can specify the absolute path to your ffmpeg executable by setting the class attribute converter, e.g.:
from pydub import AudioSegment
AudioSegment.converter = "/usr/local/bin/ffmpeg"
In older versions the class attribute used to be ffmpeg, which is deprecated now.
Solution for MacOs and compiled Python
Maybe this solution is a bit hacky and not the best way, but it actually works for me on MacOs where I had the same problem.
It solves the problem if the python script cannot access the system $PATH variable. I had to do it this way because I run my python code as a compiled binary from a java program which means for some reasons that the system $PATH variable set on my MacOs system cannot be accessed by the compiled python code.
Add this to your python code:
import os
os.environ["PATH"] += os.pathsep + '/usr/local/bin'
'/usr/local/bin' is the default for MacOs - please change it if you installed ffmpeg in a different location.
I got the idea from an answer to that question: how do I modify the system path variable in python script?
you need to this:
1- Download and extract libav from Windows binaries provided here. (http://builds.libav.org/windows/)
2- Add the libav /bin folder to your PATH envvar
Install ffmpeg then add ffmpeg.exe to your environment path, it works fine after that.

Categories

Resources