Convert audiofile from wav to mp3

Tags: #python #audio #wavtomp3 #pydub
Author: Mohit Singh
Description: This notebook uses the Pydub library to convert audio file from wav to mp3.


Download ffmpeg

!wget ""
!tar xf ffmpeg-git-amd64-static.tar.xz
!mv ffmpeg-git-20230313-amd64-static ffmpeg
import os
new_path = os.path.join(os.getcwd(), "ffmpeg")
%env PATH=$new_path

Import libraries

from pydub import AudioSegment
!pip install pydub
from pydub import AudioSegment
import requests

Setup Variables

  • audio_file_url: Link of audio file in wav to be converted to mp3
# Inputs
## link of sample wav file
audio_file_url = ''
wav_path = 'audio.wav'
mp3_path = 'audio.mp3'


Get and save audio file from URL

response = requests.get(audio_file_url)
open("audio.wav", "wb").write(response.content)

Convert wav to mp3

This code will convert the audio file from wav to mp3.
# read the WAV file using pydub
wav_audio = AudioSegment.from_file("audio.wav", format="wav")
# export the audio as MP3 using pydub
wav_audio.export(mp3_path, format="mp3")


Display result

This code will check if audio file is successfully converted to mp3.
if (os.path.isfile(mp3_path)):
print('Conversion of audio file from wav to mp3 is successful')